$(document).ready(function() {
    $('#frontpage_loginbar_username').focus(function() {
        if (this.value == 'Gebruikersnaam')
        {
             $('#frontpage_loginbar_username').css({'color': 'black', 'font-style': 'normal'});
             this.value = '';
        }
        return true;
    });
    $('#frontpage_loginbar_password').focus(function() {
        if (this.value == 'Wachtwoord')
        {
            $('#frontpage_loginbar_username').css({'color': 'black', 'font-style': 'normal'});
            this.value = '';
        }
        return true;
    });
    $('.smiley_image').click(function() {
        if (document.getElementById('message_text'))
        {
            $('#message_text').insertAtCaret($(this).attr("alt"));
        }
        else
        {
            $('#contentCommentForm_comment_form_text').insertAtCaret($(this).attr("alt"));
        }
        return true;
    });
    $('.infiniteCarousel').infiniteCarousel();
    $("#profileflirt").dialog({
        bgiframe: true,
        width: 380,
        height: 150,
        modal: true,
        autoOpen: false
    });
    $("#content_commentform").dialog({
        bgiframe: true,
        width: 380,
        height: 230,
        modal: true,
        autoOpen: false
    });
});

$.fn.extend({
    insertAtCaret: function(myValue){
            if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
            }
      else if (this.selectionStart || this.selectionStart == '0') {
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
      } else {
        this.val(this.val() + myValue);
        this.focus();
      }
    }
});

function showLoadingScreen()
{
    el = document.getElementById('loaderscreen');
    if (el)
    {
        el.style.display = 'block';
    }
}

function hideLoadingScreen()
{
    el = document.getElementById('loaderscreen');
    if (el)
    {
        el.style.display = 'none';
    }
}

$(function() {
    $("#mainmenu").lavaLamp({
        fx: "backout",
        speed: 700,
        click: function(event, menuItem) {
            return true;
        }
    });
    jQuery(document).ajaxStart(function() {
        showLoadingScreen();
    });
    jQuery(document).ajaxComplete(function() {
        hideLoadingScreen();
    });
    $('.personalCarousel').infiniteCarousel();
});

// ADD TO FAVOURITES
var favoriteToChange;

function addToFavorites(user_name, img_object, imageSize, showText)
{
    sendString = 'favorite/flipfavorite/' + user_name;

    favoriteToChange = img_object;
    favoriteImageSize = imageSize;
    favoriteShowText = showText;

    $.get(rootURL + sendString, function(data) {
        var splittedResponse = convertResponseToArray(data, ';');

        var thumbSize = '_big';
        if (favoriteImageSize == 0)
        {
            thumbSize = '';
        }

        if (favoriteShowText == 1)
        {
            document.getElementById('favorite_button_url').innerHTML = splittedResponse[2];
        }

        if (splittedResponse[0] == 1)
        {
            favoriteToChange.src = rootURL + 'images/favorietminus' + thumbSize + '.png';
        }
        else
        {
            favoriteToChange.src = rootURL + 'images/favoriet' + thumbSize + '.png';
        }
    });
}

function sendFlirt(username)
{
    var formValues = $('#flirtform').serialize();

    sendString = 'flirt/send/' + username;

    $.ajax({
        url: rootURL + sendString,
        type: "POST",
        data: formValues,
        success: function(data) {
            alert(data);
            $('#profileflirt').dialog('close');
        }
    });
}

function convertResponseToArray(response, delimiter)
{
    return response.split(delimiter);
}

function openChat()
{
    window.open("http://chat.privemailbox.nl/chatapp/chat","chat","width=962,height=700");
}

function showAllConversations()
{
    if ($('#latestconversations').css('display') == 'none')
    {
        $('#allconversations').css('display', 'none');
        $('#latestconversations').css('display', 'block');

    }
    else
    {
        $('#latestconversations').css('display', 'none');
        $('#allconversations').css('display', 'block');
    }
}

function sendRespect(username)
{
    $.get(rootURL + 'respect/' + username, function(data) {
        alert(data);
    });
}

function reverseString(str)
{
    var outputStr = '';
    for (i = 0; i < str.length; i++)
    {
        outputStr = str.charAt(i) + outputStr;
    }

    return outputStr;
}

function PMBhelp()
{
    this.helpTooltipCache = [];
    this.helpTooltipTimers = [];
}

PMBhelp.prototype.showHelpTooltip = function(index, tLeft, tTop)
{
    var oThis = this;
    $("body").prepend("<div id=" + index + " class='tip'><div class='tipMid'>"  + oThis.helpTooltipCache[index] + "</div><div class='tipBtm'></div></div>");
    var tip = $('div#' + index + '.tip');
    var topOffset = tip.height();
    var xTip = (tLeft - 30) + 'px';
    var yTip = (tTop - topOffset - 60) + 'px';
    tip.css(
    {
        top: yTip,
        left : xTip
    });
    tip.animate(
    {
        top: '+=20px',
        opacity: 'toggle'
    }, 200);
};

PMBhelp.prototype.hideHelpTooltip = function(index)
{
    var oThis = this;
    delete oThis.helpTooltipTimers[index];
    $('div#' + index + '.tip').animate(
    {
        top: '+=20px',
        opacity: 'toggle'
    },
    {
        duration: 200,
        complete: function()
        {
            $(this).remove();
        }
    });
};

var PMBhelp = new PMBhelp();


function addToMessageBlock(user_name)
{
    $.get(rootURL + 'messageblock/flipmessageblock/' + user_name, function(data)
    {
        var splittedResponse = convertResponseToArray(data, ';');
        alert(splittedResponse[1]);

        document.getElementById('messageblock_button_url').value = splittedResponse[2];
    });
};


// Everything is under a 'webcam' Namespace
window.webcam = {
    version: '1.0.9',

    // globals
    ie: !!navigator.userAgent.match(/MSIE/),
    protocol: location.protocol.match(/https/i) ? 'https' : 'http',
    callback: null, // user callback for completed uploads
    swf_url: 'webcam.swf', // URI to webcam.swf movie (defaults to cwd)
    shutter_url: 'shutter.mp3', // URI to shutter.mp3 sound
    loaded: false, // true when webcam movie finishes loading
    quality: 100, // JPEG quality (1 - 100)
    get_html: function(width, height, server_width, server_height)
    {
        // Return HTML for embedding webcam capture movie
        // Specify pixel width and height (640x480, 320x240, etc.)
        // Server width and height are optional, and default to movie width/height
        if (!server_width)
        {
            server_width = width;
        }
        if (!server_height)
        {
            server_height = height;
        }

        var html = '';
        var flashvars = 'shutter_enabled=' + (this.shutter_sound ? 1 : 0) +
            '&shutter_url=' + escape(this.shutter_url) +
            '&width=' + width +
            '&height=' + height +
            '&server_width=' + server_width +
            '&server_height=' + server_height;

        if (this.ie)
        {
            html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' + this.protocol + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="webcam_movie" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + this.swf_url + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/></object>';
        }
        else
        {
            html += '<embed id="webcam_movie" src="' + this.swf_url + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="webcam_movie" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" />';
        }

        this.loaded = false;

        return html;
    },
    flash_notify: function(type)
    {
        switch(type)
        {
            case 'flashLoadComplete':
                this.loaded = true;
                $('#webcamContainer input').show();
                break;
            case 'noCam':
                this.loaded = false;
                $('#webcamContainer').hide();
                break;
            case 'noImage':
                alert("Er is iets fout gegaan, ververs de pagina en probeer het opnieuw");
                break;
        }
    },

    get_movie: function()
    {
        // get reference to movie object/embed in DOM
        if (!this.loaded)
        {
            alert("De webcam is nog niet geladen, een ogenblik geduld a.u.b.");
            return false;
        }

        var movie = document.getElementById('webcam_movie');
        if (!movie)
        {
            alert("Er is iets fout gegaan, ververs de pagina en probeer het opnieuw");
            return false;
        }

        return movie;
    },

    snap: function()
    {
        var movie = this.get_movie();
        if (movie)
        {
            movie._snap(this.api_url, this.quality, this.shutter_sound ? 1 : 0, this.stealth ? 1 : 0 );
        }
    },

    reset: function()
    {
        var movie = this.get_movie();
        if (movie)
        {
            movie._reset();
        }
    },

    flash_image_catcher: function(data)
    {
        var boundary = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        for (var i = 0; i < 20; i++)
        {
            boundary += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        var body = "--" + boundary + "\r\n";
        body += "Content-Disposition: form-data; name='Filedata'; filename='webcam.jpg'\r\n";
        body += "Content-Type: image/jpeg\r\n\r\n";
        body += data + "\r\n";
        body += "--" + boundary + "\r\n";
        body += "Content-Disposition: form-data; name='base64'\r\n";
        body += "Content-Type: application/octet-stream\r\n\r\n";
        body += "1\r\n";
        body += "--" + boundary + "\r\n";
        body += "Content-Disposition: form-data; name='Filename'\r\n";
        body += "Content-Type: application/octet-stream\r\n\r\n";
        body += "webcam.jpg\r\n";
        body += "--" + boundary + "\r\n";
        body += "Content-Disposition: form-data; name='folder'\r\n";
        body += "Content-Type: application/octet-stream\r\n\r\n";
        body += "/account/uploads\r\n";
        body += "--" + boundary + "--";
        $.ajax(
        {
            cache: false,
            contentType: "multipart/form-data, boundary=" + boundary,
            data: body,
            url: rootURL + 'account/photo/upload',
            type: "POST",
            success: function(d)
            {
                onPhotoPostComplete('', '', '', d, '');
            }
        });
        this.reset();
    }
};
