$(document).ready(function() {

    dummyLinkHandlers();
    loginHandlers('#mainLogin');
    videoSearchHandlers();

    $("#lang_english").click(function() {

        $("#english_comingSoon").overlay(overlayconfig).load();
        return false;
    });

    $("#bannerPatrocinado").flashembed( {
        version: [ 9 ],
        allowscriptaccess: true,
        allowfullscreen: true,
        expressInstall: '/swf/expressInstall.swf',
        src: '/swf/bannerPatrocinado.swf',
        width: 483,
        height: 239,
        wmode: 'opaque',
        cachebusting: false
    });

    $(".lock").live('click', function() {
        $("#userNeedsLogin").overlay(overlayconfig).load();
        $("#userNeedsLogin").css(overlayOverrides);
        return false;
    });

    $("#open_forgotPass").click(function() {
        user_forgotPassShowControls();
        return false;
    });

    $("#open_forgotPassTop").click(function() {
        user_forgotPassShowControls();
        return false;
    });

    // Disable right mouse click
    $(document)[0].oncontextmenu = function() {return false;};



});

    // Limit elements on AddThis over area
var addthis_config = {
	services_compact: 'email,print,twitter,facebook,myspace,blogger,favorites,live,orkut,sportpost'
};


var overlayconfig = {
    expose: {
        color: '#666',
        loadSpeed: 200,
        opacity: 0.9
    },
    left: 'center',
    closeOnClick: false,
    oneInstance: true,
    api: true
};

var overlayOverrides = {
    position: 'fixed',
    top: '40px'
};

function loginHandlers(formSelector, callbackOnSuccess) {

    $(formSelector + " input").focus(function() {

        var me = $(this);
        if (!me.hasClass('dirty')) {
            $(this).val('');
            me.addClass('dirty');
        }
    });

    $(formSelector + " .loginSubmit").click(function() {

        var form = $(this).closest('form');
        var data = new Object();
        data.email      = form.find('input.email').val();
        data.password   = form.find('input.password').val();
        if (form.find('input.rememberme').attr('checked'))
            data.rememberme = form.find('input.rememberme').attr('checked');
        $(".login_form").hide();
        $(".login_waiting").show();

        $.getJSON('/ajax/login', data, function(json) {

            if (json['success']) {
                if (callbackOnSuccess != null) {
                    callbackOnSuccess();
                } else {
                    reloadPage();
                }
                return false;
            } else {
                showGenericOverlay('El usuario o la clave son incorrectos, o todavía no has validado tu dirección de email');
                $(".login_waiting").hide();
                $(".login_form").show();
            }
        });

        return false;
    });
}

function reloadPage() {

    var sURL = unescape(window.location.pathname);
    window.location.replace(sURL);
}

function videoPlayerHandlers(width, height, withTouch) {

    if (withTouch == undefined) {
        withTouch = true;
    }

    // Show first video info
    $("#video_info_0").show();

    // jwplayer
    $(".playVideo").unbind('click');
    $(".playVideo").live('click', function() {

        // Unselect all <li>
        $(".playVideo").parent('li').removeClass('selected');

        // Select this one only
        $(this).parent('li').addClass('selected');

        var videoId = getSuffix($(this).attr('id'));

        // Handle video title
        var titulo = $(this).attr('title');
        $("#currentVideoTitle").html(titulo);

        // Hide all video info divs
        $("#videoInfoContainers div").hide();

        // Show the currently being played one
        $("#video_info_" + videoId).show();

        loadVideoById(videoId, "videoPlayerHolder", width, height, false);
        return false;
    });
}
function loadVideoById(videoId, targetElement, videoWidth, videoHeight, withTouch) {

    // Since SWFObject 2.0 the WHOLE container is replaced, so this is a
    // simple hack that will create a dummy container in which to load the videos
    var flashTarget = "videoPlayerHolder";
    $("#" + flashTarget).html('').append('<div id="videoPlayer_holder"></div>');

    // Codistream ON DEMAND player with "touch"
    var vars        = { videoToShow: videoId,
                           isLogged: system_userIsLogged,
                         videoWidth: videoWidth,
                        videoHeight: videoHeight };

    var params      = {             scale: "noScale",
                                     menu: "false",
                          allowFullScreen: "true",
                        allowScriptAccess: "always" };

    var attributes  = {   id: "swfID",
                        name: "swfID" };

    swfobject.switchOffAutoHideShow();

    if (withTouch) {
        playerUrl = "http://progressive01.codistream.net/userdata/santamonicaapi/PlayerTouch.swf";
    } else {
        playerUrl = "http://progressive01.codistream.net/userdata/santamonicaapi/PlayerOnDemand.swf";
    }

    swfobject.embedSWF(playerUrl, "videoPlayer_holder", videoWidth, videoHeight, "10",
    "http://progressive01.codistream.net/generalFiles/swfjs/expressInstall.swf", vars, params, attributes);

}

function loadVideoById2(videoId, targetElement, width, height, autostart) {

    // Since SWFObject 2.0 the WHOLE container is replaced, so this is a
    // simple hack that will create a dummy container in which to load the videos
    $("#" + targetElement).html('')
                          .append('<div id="videoPlayer_holder"></div>');

    if (autostart == undefined) {
        autostart = true;
    }

    var vars        = {
            file: '/ajax/videos/playlist/' + videoId + '.xml',
            skin: '/swf/jwplayer/modieus.swf',
            controlbar: 'over',
            autostart :  autostart,
            repeat    : 'list',
            frontcolor: 'ffffff',
            backcolor : 'da0019',
            lightcolor: 'ffffff',
            stretching: 'uniform'
    };
    var params      = { scale: "noScale", menu:"false", allowFullScreen: "true", allowScriptAccess: "always" };
    var attributes  = { id: "swfID", name: "swfID" };

    swfobject.switchOffAutoHideShow();
    swfobject.embedSWF("/swf/jwplayer/player-licensed.swf", 'videoPlayer_holder', width, height, "10", "", vars, params, attributes);

}

function loadVideoById3(videoId, targetElement, videoWidth, videoHeight, withTouch) {

    // Since SWFObject 2.0 the WHOLE container is replaced, so this is a
    // simple hack that will create a dummy container in which to load the videos
    // var flashTarget = "videoPlayerHolder";
    $("#" + targetElement).html('').append('<div id="videoPlayer_holder"></div>');

    // Codistream ON DEMAND player with "touch"
    var vars        = { videoToShow: videoId,
                           isLogged: system_userIsLogged,
                         videoWidth: videoWidth,
                        videoHeight: videoHeight };

    var params      = {             scale: "noScale",
                                     menu: "false",
                          allowFullScreen: "true",
                        allowScriptAccess: "always" };

    var attributes  = {   id: "swfID",
                        name: "swfID" };

    swfobject.switchOffAutoHideShow();

    if (withTouch) {
        playerUrl = "http://progressive01.codistream.net/userdata/santamonicaapi/PlayerTouch.swf";
    } else {
        playerUrl = "http://progressive01.codistream.net/userdata/santamonicaapi/PlayerOnDemand.swf";
    }

    swfobject.embedSWF(playerUrl, "videoPlayer_holder", videoWidth, videoHeight, "10",
    "http://progressive01.codistream.net/generalFiles/swfjs/expressInstall.swf", vars, params, attributes);

}

function loadTransmisionById(transmisionId, targetElement, width, height, autostart) {

    $("#" + targetElement).html('')
    .append('<div id="videoPlayer_holder"></div>');

    if (autostart == undefined) {
        autostart = true;
    }

    var vars        = {
            file: '/ajax/videos/playlist/transmision/' + transmisionId + '.xml',
            skin: '/swf/jwplayer/modieus.swf',
            controlbar: 'over',
            autostart :  autostart,
            repeat    : 'list',
            frontcolor: 'ffffff',
            backcolor : 'da0019',
            lightcolor: 'ffffff',
            stretching: 'uniform'
    };
    var params      = { scale: "noScale", menu:"false", allowFullScreen: "true", allowScriptAccess: "always" };
    var attributes  = { id: "swfID", name: "swfID" };

    swfobject.switchOffAutoHideShow();
    swfobject.embedSWF("/swf/jwplayer/player-licensed.swf", 'videoPlayer_holder', width, height, "10", "", vars, params, attributes);
   
}

function videos_categoryIdHandler(comboId) {

    $("#" + comboId).change(function() {

        var galleryId = $(this).val();
        var galleryName = $("#" + comboId + " option[value=" + galleryId + "]").html();

        videos_updateTitles();

        if (galleryId == '') {
            // Combo is empty so exit silently
            return false;

        } else {
            // Bring all videos for the selected gallery
            $("#videoGalleryWrapper").hide('fast');

            $("#videoGalleryWrapper").load('/ajax/videos/get_galleries/' + galleryId, {}, function(html) {

                $(this).show('normal');
                videoPlayerHandlers(720, 421, false);
            });
        }
    });
}

function videos_updateTitles() {

    var galleryId = $("#videoGalleryId1").val();
    var galleryName = $("#videoGalleryId1 option[value=" + galleryId + "]").html();

    $(".categoryTitle").html(galleryName);
}


function news_sidebarPagerHandler() {

    $("#newsPager").change(function() {

        $("#sidebarWrapper").hide('fast');

        var data = new Object();
        data.page = $(this).val();

        $("#sidebarWrapper").load('/ajax/news_sidebar', data, function(html) {

            $(this).show('normal');
            news_sidebarPagerHandler();
        });
    });
};


function dummyLinkHandlers() {

    // Prevent links with the class "dummyLink" from executing
    $(".dummyLink").click(function() {

        return false;
    });
}

function videoSearchHandlers() {

    $("#searchSubmit").click(function() {

        var keywords = $("#searchForm #s").val();
        if (keywords == '' || keywords == null) {
            showGenericOverlay('Debe ingresar por lo menos un término de búsqueda');
            return false;
        }

        location.href = '/videos-search/' + system_language + '/' + keywords;

        return false;
    });
}



function user_resetPassShowControls(callbackOnSuccess) {
    var api = $("#over_changePass").overlay(overlayconfig).load();
    user_resetPassHandlers(api, callbackOnSuccess);
}

function user_resetPassHandlers(overlayApi, callbackOnSuccess) {
    var jLoading = $("#over_changePass .loading");
    var jEnviarBtn = $("#over_changePass .enviarChangePass");
    
    $("#over_changePass .enviarChangePass").click(function(){
        var data = new Object();
        data.pass1 = $("#over_changePass .pass1").val();
        data.pass2 = $("#over_changePass .pass2").val();
        data.email = $("#over_changePass .email").val();
        data.code  = $("#over_changePass .code").val();
        
        $("#over_changePass .mensajeError").hide();
        jEnviarBtn.hide();
        jLoading.show();
        
        $.getJSON('/ajax/resetPass', data, function(json) {
            jEnviarBtn.show();
            jLoading.hide();
            
            if (json['success']) {
                $("#over_changePass .paso1").hide();
                $("#over_changePass .paso2").show();
                if (callbackOnSuccess != null) {
                    overlayApi.onClose(function(){
                        callbackOnSuccess();
                    });
                }
            } else {
                $("#over_changePass .mensajeError").show();
                $("#over_changePass .errorList").html(json['message']);
            }
        });
        
        return false;
    });
}

function user_forgotPassShowControls(callbackOnSuccess) {
    $("#over_forgotPass .paso1").show();
    $("#over_forgotPass .paso2").hide();
    var api = $("#over_forgotPass").overlay(overlayconfig).load();
    user_forgotPassHandlers(api, callbackOnSuccess);
}

function user_forgotPassHandlers(overlayApi, callbackOnSuccess) {
    $("#over_forgotPass .enviarForgot").click(function(){

        var data = new Object();
        data.email = $("#over_forgotPass .email").val();


        $("#over_forgotPass .mensajeError").hide();
        $("#over_forgotPass .enviarForgot").hide();
        $("#over_forgotPass .loading").show();

        $.getJSON('/ajax/requestNewPass', data, function(json) {
            $("#over_forgotPass .enviarForgot").show();
            $("#over_forgotPass .loading").hide();

            if (json['success']) {
                $("#over_forgotPass .mensajeError").hide();
                $("#over_forgotPass .paso1").hide();
                $("#over_forgotPass .paso2").show();
                if (callbackOnSuccess != null) {
                    overlayApi.onClose(function(){
                        callbackOnSuccess();
                    });
                }
            } else {
                $("#over_forgotPass .mensajeError").show();
                $("#over_forgotPass .errorList").html(json['message']);
            }
        });
        
        return false;
    });
}

function showGenericOverlay(text, callbackOnSuccess) {
    
    $("#genericOverlay .genericText").html(text);
    
    var api = $("#genericOverlay").overlay(overlayconfig).load();
    
    if (callbackOnSuccess != null) {
        api.onClose(function(){
            callbackOnSuccess();
        });
    }
}

function getSuffix(id, separator) {

    // take a string like "some_text_id_56"
    // and grab only the part after the last underscore
    if (separator == undefined) {
        separator = '_';
    }
    var arr = id.split(separator);
    return arr[arr.length - 1];
}


/**
 * 
 * URL encode / decode http://www.webtoolkit.info/
 * 
 */

var UrlTools = {

    // 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;
    }

};

function IsNumeric(sText) {

    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;

}


