var lastBtnId = null;
var twitterLoginPopup = null;
var loginPopup = null;
var notificationTimeout = null;
var disabledButtons = new Array();
var blockedButtons = new Array();

// onload function
$(document).ready(function() {
/*    // do default actions if logged in (whatever auth)
    if (typeof(window['g_loggedIn']) != "undefined" && g_loggedIn) {
        if (typeof(onLogin) != "undefined") {
            onLogin({userBid: g_userBid});
        }
    } else {
        if (typeof(onLogout) != "undefined") {
            onLogout(null);
        }
    }

    // do default actions when logged in on twitter
    if (typeof(g_loggedInOnTwitter) != "undefined" && g_loggedInOnTwitter) {
        if (typeof(onTwitterLogin) != "undefined") {
            onTwitterLogin({userBid: g_userBid});
        }
    } else {
        if (typeof(onTwitterLogout) != "undefined") {
            onTwitterLogout(null);
        }
    }*/

    // look if a message is available in cookies
    var successMessage = $.cookie('successMessage');
    if (successMessage) {
        showNotificationBar('success',successMessage);
        $.cookie('successMessage',null,{path: '/'});
    }
});

window.hideNotificationBar = function() {
    $('#notification-bar').hide();

    if (notificationTimeout != null) {
        clearTimeout(notificationTimeout);
    }

    notificationTimeout = null;
};

window.showNotificationBar = function(type,text, twitterPopupLink) {
    if ($('#notification-bar').length === 0) {
        $('body').append('<a href="#" onclick="hideNotificationBar(); return false;"><div class="hidden" id="notification-bar"><div class="content"></div><div class="background"></div></div></a>');
    } else {
        hideNotificationBar();
    }

    if(twitterPopupLink == 'twitter') {
        text = text +'<br/><a style="color: blue;" href="#" onclick="openTwitterPopup(); return false;">Open Twitter sign in popup</a>';
    } else {
        notificationTimeout = setTimeout(hideNotificationBar, 5000);
    }

    $('#notification-bar').find('.content').html(text);
    if (type == 'error') {
        $('#notification-bar').find('.background').css('background-color','#F5B5A1');
    } else {
        $('#notification-bar').find('.background').css('background-color','#B5F5A1');
    }

    $('#notification-bar').animate({
        height: 'show'
    }, 100);
};

window.setDefaultText = function(inputId, text) {
    $('body').append('<div class="hidden" id="'+inputId+'DefaultText">'+text+'</div>');
    // change the value to the default one if not empty
    if ($('#'+inputId).val().length === 0) {
        $('#'+inputId).val(text);
        $('#'+inputId).css('color','#333333');
    }

    $('#'+inputId).focus(function() {
        var defText = $('#'+inputId+'DefaultText').html();
        if(this.value == defText) {
            this.value = '';
        }
        $('#'+inputId).css('color','#000000');
    });

    $('#'+inputId).blur(function() {
        var defText = $('#'+inputId+'DefaultText').html();
        if(this.value == '') {
            this.value = defText;
            $('#'+inputId).css('color','#333333');
        } else {
            $('#'+inputId).css('color','#000000');

        }
    });
};

//When the user clicks on terms and condition : show inline
window.onClickTermsAndCondition = function() {
    if ($('#eula-content').is(':visible')) {
        $('#eula-content').animate({
            height: 'hide'
        }, 'slow');
    } else {
        $('#eula-content').animate({
            height: 'show'
        }, 'slow');
    }
};

window.sendEvent = function(eventType, videoBid, meta1, meta2, meta3) {
    var	data = {
        event_type: eventType
    };

    if (videoBid) { data.video_bid = videoBid; }
    if (meta1) { data.meta1 = meta1; }
    if (meta2) { data.meta2 = meta2; }
    if (meta3) { data.meta3 = meta3; }

    // call event service
    $.ajax({
        type: 'GET',
        url: g_postEventUrl,
        cache: false,
        data: data,
        success: function(msg) {}
     });
};

/*
* Update information for a given video identified by its video_bid
*/
window.updateVideoInformations = function(videoBid, description, published, successCallback, errorCallback) {
    alert('updateVideoInformations deprecated use screenjelly.saveVideo instead');
    /*ajaxCall({
         type: 'POST',
         async: false,
         showSuccess: false,
         url: g_updateVideoInformationsUrl,
         data: {
             'videoBid' : videoBid,
             'description' : description,
             'published' : published
         },
         cache: false,
         onSuccess: function(data){
            if(successCallback) { successCallback(data); }
         },
         onError: function (code, error) {
            if(errorCallback) { errorCallback(code, error); }
         }
    });
    */
};

/*
* Update description for a given video identified by its video_bid
*/
window.updateVideoDescription = function(videoBid, description, successCallback, errorCallback) {
    ajaxCall({
         type: 'POST',
         async: false,
         showSuccess: false,
         url: g_updateVideoDescriptionUrl,
         data: {
             'videoBid' : videoBid,
             'description' : description
         },
         cache: false,
         onSuccess: function(data){
            if(successCallback) { 
                $(document).ready(function ()
                {
                  document.title = 'Screenjelly - ' + description;
                });
                successCallback(data); 
            }
         },
         onError: function (code, error) {
            if(errorCallback) { errorCallback(code, error); }
         }
    });
};

window.ajaxCall = function(config) {
    config.success = function (msg) {
        try {
            if (msg) {
                // Avoid eval if possible
                var jsonObject = null;
                jsonObject = JSON.parse(msg);
                //response = eval("("+msg+")");
                
                var errors = false;
                if (config.manageErrors == null || config.manageErrors == true) {
                    if (jsonObject == null) {
                        if (config.onError) {
                            config.onError('NO_DATA', null);
                        }
                    } else if (jsonObject.status != 'success') {
                        errors = true;

                        if (jsonObject.fieldErrors) {
                            for (var i=0; i<jsonObject.fieldErrors.length; i++) {
                                $('#'+jsonObject.fieldErrors[i].field+'-error').html(jsonObject.fieldErrors[i].message);
                                $('#'+jsonObject.fieldErrors[i].field+'-error-icon').show();
                            }
                            if(jsonObject.data == null) {
                                jsonObject.data = {};
                            }
                            jsonObject.data.fieldErrors = jsonObject.fieldErrors;
                        }

                        if (config.showError == null || config.showError == true) {
                            if (jsonObject.errorMessage && jsonObject.errorMessage != null) {
                                if (config.useBubble) {
                                    $('#'+config.useBubble).attr('class','bubble-red');
                                    $('#'+config.useBubble).find('.bubble-text').html(jsonObject.errorMessage.message);
                                    $('#'+config.useBubble).show();
                                } else {
                                    showNotificationBar('error',jsonObject.errorMessage.message);
                                }
                            }
                        }
                    } else {
                        if (config.showSuccess == null || config.showSuccess == true) {
                            if (jsonObject.successMessage && jsonObject.successMessage != null) {
                                if (config.useBubble) {
                                    $('#'+config.useBubble).find('.bubble-text').html(jsonObject.successMessage);
                                    $('#'+config.useBubble).attr('class','bubble-green');
                                    $('#'+config.useBubble).show();
                                } else {
                                    showNotificationBar('success',jsonObject.successMessage);
                                }
                            }
                        }
                    }
                }

                if (!errors) {
                    if (config.onSuccess) {
                        config.onSuccess(jsonObject.data, jsonObject);
                    } else { }
                } else {
                    if (config.onError) {
                        config.onError('RECEIVED_ERRORS', jsonObject.data, jsonObject);
                    }
                }
            } else {
                showNotificationBar('error','Oops, an error occured. Please try again later.');
                logger.error('Ajax Error: no data received');
                if (config.onError) {
                    config.onError('DATA_RECEIVED', null);
                }
            }
        } catch (errorThrown) {
            showNotificationBar('error','Oops, an error occured. Please try again later.');
            logger.error('Ajax Error',errorThrown);
            if (config.onError) {
                config.onError('JSON_PARSING',errorThrown);
            }
        }
    };

    config.error = function (XMLHttpRequest, textStatus, errorThrown) {
        showNotificationBar('error','Oops, an unexpected error occured. Please try again later.');
        logger.error('Ajax Error:'+textStatus+' (status:'+XMLHttpRequest.status+')',errorThrown);
        if (typeof config.onError == 'function') {
            config.onError('FATAL_ERROR',errorThrown);
        }
    };

    if (logger.level == log4js.levels.debug) { logger.trace(config); }
    logger.parachute(config);

    $.ajax(config);
};

window.addCounterField = function(text,input,maxvalue,button) {
    $('#'+input).keyup(function(event){
        logger.parachute(updateCounter(text,input,this.value.length,maxvalue,button));
    });
    $('#'+input).click(function(event){
        logger.parachute(updateCounter(text,input,this.value.length,maxvalue,button));
    });
    $('#'+input).blur(function(event){
        logger.parachute(updateCounter(text,input,this.value.length,maxvalue,button));
    });

    $('#'+input).keyup();
};

window.disableButton = function(buttonId) {
    var button = $('#'+buttonId);

    if (button.attr('class') == 'button-bgray') {
        button.attr('class','button-bgray-inactive');
    }
    if (button.attr('class') == 'button-gray') {
        button.attr('class','button-gray-inactive');
    }

    var i = disabledButtons.length;
    disabledButtons[i] = new Array();

    // get old values
    disabledButtons[i][0] = $(button).attr('id');
    disabledButtons[i][2] = $(button).find('a').attr('onclick');

    // change values
    $(button).find('a').each(function(){
        this.onclick = function (event) { return false; };
    });
};

window.enableButton = function(buttonId) {
    var button = $('#'+buttonId);

    if (button.attr('class') == 'button-gray-inactive') {
        button.attr('class','button-gray');
    }
    if (button.attr('class') == 'button-bgray-inactive') {
        button.attr('class','button-bgray');
    }

    for (i=0; i<disabledButtons.length; i++) {
        if(disabledButtons[i][0] == $(button).attr('id')) {
            // change values
            $(button).find('a').each(function(){
                this.onclick = disabledButtons[i][2];
            });

            // remove from array
            disabledButtons = jQuery.grep(disabledButtons, function(value) {
                return value[0] != $(button).attr('id');
            });
        }
    }
};

window.updateCounter = function(text,input,size,maxvalue,button) {
    var diff = maxvalue - size;

    $('#'+text).html(diff+' characters left');
    if (diff < 0) {
        $('#'+text).css('color','red');
        $('#'+input).css('color','red');

        if (button !== null) {
            if ($('#'+button).attr('class') == 'button-bgray') {
                $('#'+button).attr('class','button-bgray-inactive');
            }
            if ($('#'+button).attr('class') == 'button-gray') {
                $('#'+button).attr('class','button-gray-inactive');
            }
        }
    } else {
        $('#'+text).css('color','#333333');
        if ($('#'+input).css('color') == 'red') {
            $('#'+input).css('color','black');
        }

        if (button !== null) {
            if ($('#'+button).attr('class') == 'button-gray-inactive') {
                $('#'+button).attr('class','button-gray');
            }
            if ($('#'+button).attr('class') == 'button-bgray-inactive') {
                $('#'+button).attr('class','button-bgray');
            }
        }
    }
};

// block a button
window.blockButton = function(button, text) {
    var i = blockedButtons.length;
    blockedButtons[i] = new Array();

    // get old values
    blockedButtons[i][0] = $(button).attr('id');
    blockedButtons[i][1] = $(button).find('.button-text').html();
    blockedButtons[i][2] = $(button).find('a').attr('onclick');

    // change values
    $(button).find('a').each(function(){
        this.onclick = function (event) { return false; };
    });
    $(button).find('.button-text').html(text);
};

// unblock a button
window.unblockButton = function(button) {
    for (i=0; i<blockedButtons.length; i++) {
        if(blockedButtons[i][0] == $(button).attr('id')) {
            // change values
            $(button).find('a').each(function(){
                this.onclick = blockedButtons[i][2];
            });
            $(button).find('.button-text').html(blockedButtons[i][1]);

            // remove from array
            blockedButtons = jQuery.grep(blockedButtons, function(value) {
                return value[0] != $(button).attr('id');
            });
        }
    }
};

//the user clicks on a tab
window.onClickTab = function(tabId, btnId) {
    if (lastBtnId != btnId) {
        $('.tabs').children('div').attr('class','button-green');
        $('#'+btnId).attr('class','button-lgreen');
        $('.tab-content').children().hide();
        $('#'+tabId+'-tab').show();
        $('#share-tabs').show();
    } else {
        if ($('#'+tabId+'-tab').is(':visible')) {
            $('.tabs').children('div').attr('class','button-green');
            $('.tab-content').children().hide();
            $('#share-tabs').hide();
        } else {
            $('#'+btnId).attr('class','button-lgreen');
            $('#'+tabId+'-tab').show();
            $('#share-tabs').show();
        }
    }

    lastBtnId = btnId;

/*	if (lastTabElement != element) {
        $(element).parent().parent().children('div').attr('class','button-green');
        $(element).parent().attr('class','button-lgreen');
        $('.tab-content').children().hide();
        $('#'+tabId+'-tab').show();
        $('#share-tabs').show();
    } else {
        if ($('#'+tabId+'-tab').is(':visible')) {
            $(element).parent().parent().children('div').attr('class','button-green');
            $('.tab-content').children().hide();
            $('#share-tabs').hide();
        } else {
            $(element).parent().attr('class','button-lgreen');
            $('#'+tabId+'-tab').show();
            $('#share-tabs').show();
        }
    }

    lastTabElement = element;*/
};

window.showTooltip = function(divId, element, revertIfNeeded) {
    $('#tooltip').remove();

    var htmlContent = $('#'+divId).html();
    if (htmlContent === null || htmlContent.length === 0) { return ; }

    var className = 'tooltip';

    if (revertIfNeeded && $(window).width() < 1075) {
        className = 'tooltip-revert';
    }

    var tooltipHtml = '<div id="tooltip" class="'+className+'"><div class="tooltip-top"></div><div class="tooltip-middle">'+htmlContent+'</div><div class="tooltip-bottom"> </div></div>';

    $(element).parent().parent().append(tooltipHtml);

    var top = -$('#tooltip').height()-10;
    $('#tooltip').css('top', top+'px');

    if (revertIfNeeded && $(window).width() < 1075) {
        $('#tooltip').css('left', '-85px');
    }
};

window.hideTooltip = function() {
    $('#tooltip').remove();
};

window.showHelpTip = function(divId, element) {
    $('#helptip').remove();

    var htmlContent = $('#'+divId).html();
    if (htmlContent === null || htmlContent.length === 0) { return ; }

    var className = 'helptip';

    var helptipHtml = '<div id="helptip" class="'+className+'"><div class="helptip-top"></div><div class="helptip-middle">'+htmlContent+'</div><div class="helptip-bottom"> </div></div>';

    $(element).append(helptipHtml);
};

window.hideHelpTip = function() {
    $('#helptip').remove();
};

window.isSafariMac = function() {
    // check if safari on mac
    var mac = (navigator.userAgent.toLowerCase().indexOf("mac")!=-1) ? true: false;
    return mac && $.browser.safari;
};

window.updateCaptcha = function(imageId, hiddenFieldId) {
    // Ask for a captcha key
    ajaxCall({
        type: 'GET',
        url: g_generateCaptchaUrl,
        onSuccess: function(data) {
            $('#'+hiddenFieldId).val(data.captchaCode);
            $('#'+imageId).attr('src', g_displayCaptchaUrl+data.captchaCode);
        },
        onError: function(code, error) {

        }
    });
};

// simulate a click on a button for every child element of what
window.addEnterCallback = function(what, button) {
    jQuery(what).find('input').each(
        function(index) {
            this.onkeydown = function(event) {
                if(!event) { event = window.event; }
                if(event.keyCode == 13) {
                    $(button).find('a:first').click();
                }
            };
        }
    );
};

window.openPopup = function(url, name, args, onCloseCallback) {
    // open and focus on the popup
    var popup = window.open(url, name, args);

    // was the popup open (or blocked)
    if (popup) {
        // focus the popup
        popup.focus();

        // if there is a callback
        if (onCloseCallback) {
            // add callback on popup closed
            var interval;
            interval = setInterval(function () {
                // wait for the popup to be closed
                if (popup.closed) {
                    clearInterval(interval);
                    if (onCloseCallback) {
                        onCloseCallback();
                    }
                }
            }, 250);
        }
    } else {
        showNotificationBar('error', 'Popup blocked, please click on the link below:', 'twitter');
    }
    // return popup reference
    return popup;
};

window.getParameterFromUrl = function(name, url) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( arguments[1]?arguments[1]:window.location.href );
    if( results === null ) {
          return null;
    } else {
        return results[1];
    }
};

window.onClickAskScreenjelly = function(zen) {
    zen.render();
};

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}