
function preloadImg(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    // Alternatively you could use:
    // (new Image()).src = this;
    });
}

function initMenu() {
    $('#menuCat ul').hide();
    $('#menuCat ul:first').show();
    $('#menuCat li span').click(
        function(e) {
        
            var contentDiv = $(this).next("ul");
            var checkElement = $(this).next();
            var relId = $(this).attr("rel");

            $.ajax({
                url: '/categories/index/load-Sub-Categories/cat/'+relId+'',
                beforeSend: function(){
                    $('#ajaxLoad'+relId).show();
                },
                success: function(data) {
                    $(contentDiv).html(data);
                    $('#ajaxLoad'+relId).fadeOut();
                    if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                        return false;
                    }
                    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                        $('#menuCat ul:visible').slideUp('normal');
                        checkElement.slideDown('normal');
                        return false;
                    }
                }
            });
        
        }
        );
}

function showComments ( id, realtimeId, refresh ) {
    
    if( typeof(realtimeId) == 'undefined' ) { var realtimeId = id ;}
    
    if( $("#comments_" + realtimeId ).is( ":visible" ) && refresh == false ) {
        $( "#comments_" + realtimeId ).fadeToggle( "normal", "linear" );
    } else {
        //$.post( SERVER_URL + "/" + COUNTRY + "/api/social/?type=comment&realtimeId="+realtimeId, { id: id }, function ( data ) {
        $.post( SERVER_URL + "/social/comments/ajax/format/json/", { product_country_id: id, type: "comment", realtime_id: realtimeId }, function ( data ) {

            $( "#comments_" + realtimeId ).html( data.html_comments );
            $( "#productNumComments_" + realtimeId  ).html( "<span class='productNumCommentsNumber'>" + data.count_comments + "</span>" );

            if( refresh == false ) {
                $( "#comments_" + realtimeId ).fadeToggle( "normal", "linear" );
            }
        } );
    
    }
}


$(document).ready(function() {
    
    preloadImg([
        '/images/layout/header/cat_arrow_blue.png',
        '/images/layout/header/cat_bt_bg_over.png',
        '/images/layout/header/menu_bg_over.jpg',
        '/images/layout/header/img_search_back.png',
        '/images/layout/header/img_search_icon.png',
        '/images/layout/header/img_search.png',
        "/images/loading.gif",
        "/images/layout/menu_header/cat_up_arrow.png",
        ]);
        

    // Init categories menu.
    //initMenu();

    // SubMenu Cats
    /*$("#kactoosMenuCont").hover(
      function () {
        $("#kactoosMenu").fadeIn();
      }
    );

    $("#kactoosMenuCloseImg").click(
        function() {
            $("#kactoosMenu").fadeOut();
        });
    */




    $('.viewCouponInput').click(
        function() { $("#CouponInput").slideToggle();  $('#InputCoupon').focus(); }
    );

    $('.addfriend').click(
        function() {
            var relId = $(this).attr("id");
            $(this).addClass('grayButtonBig');
            $(this).removeClass('orangeButtonBig');

            $.ajax({
                url: '/users/index/add-friend/user_id/'+relId+'',
                success: function(data) {
                    $('#'+relId).html(data);

                }
            });

        }
        );

   
        
    $('#jsddm > li').bind('mouseover', jsddm_open);
    $('#jsddm > li').bind('mouseout',  jsddm_timer);

    $(".kactoos-seguro").fancybox({
        'titlePosition': 'inside',
        'transitionOut': 'none',
        'padding': 0,
        'margin': 0,
        'centerOnScroll': 'TRUE',
        'scrolling':   'no'
    });

    $(".kactoos-update").fancybox({
        'padding': 0,
        'margin': 0,
        'centerOnScroll': true,
        'scrolling':   'no',
        'transitionIn'		: 'none',
        'transitionOut'		: 'none'
    });

    
    // Testimonials Videos
    $(".videoTestimonio").fancybox({
        'type'          : 'swf',
        'centerOnScroll': true,
        'padding': 0,
        'margin': 0
    });

    // Load Ajax
    $(".load_ajax").fancybox({
        ajax : {
            type	: "POST"
        }
    });

    $(".fancyframe").fancybox({
        'type': 'iframe',
        'scrolling': 'yes',
        height: 600,
        width: 620,
        'centerOnScroll': false,
        'titleShow'     : false
    });


    $(".box").fancybox({
        'centerOnScroll': 'TRUE'
    });


    // Autocomplete for the search
    $("#searchBox").autocomplete( "/search/index/search-products-autocomplete", {
        width: 240,
        max: 10,
        highlight: false,
        scroll: true,
        selectFirst: false,
        scrollHeight: 300,
        formatItem: function(data, i, n, value) {
            //return "<img src='/images/products/" + value.split("¬")[0] + "' width='20' alt=''  /><span>" + value.split("¬")[1] + "</span>";
            return "<a href='" + value.split("¬")[2] + "' ><img src='/libraries/thumb/?src=/images/products/" + value.split("¬")[0] + "&w=20' width='20' alt='Product'  /><span>" + value.split("¬")[1] + "</span></a>";
        },
        formatResult: function(data, value) {
            return value.split("¬")[1];
        }
    }).result( function(event, item ) {
        alert( item.split("¬")[2] );
    /*location.href = item.split("¬")[2];*/
    }) ;


    $(".fancy").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        fixPNG: true,
        showBody: " - ",
        extraClass: "pretty fancy",
        top: -15,
        left: 5
    });

    $(".fancy2").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        fixPNG: true,
        showBody: " - ",
        extraClass: "pretty2 fancy",
        top: -15,
        left: 5
    });


    // Validate checkbox registration_terms
    $('.val_check').click(function()
    {
        var registration_terms = $('#registration_terms').is(':checked');

        if (registration_terms == true)
        {
            $('#btnSave').attr('disabled', false);
            $('#btnSaveWeb').attr('disabled', false);
            $('#btnSave').fadeIn();
            $('#btnSaveWeb').fadeIn();
            $('#joinFlecha').hide();
        }
        else
        {
            //$('#btnSave').hide();
            //$('#btnSaveWeb').hide();
            $('#joinFlecha').fadeIn();
        }
    });

    //Desactivate the button JOIN in add.phtml when the user has click
    $('#btnSaveProduct').click(function()
    {
            $(this).hide();
            $("#loadingJoinButton").show();
            //$(this).attr('disabled', 'disabled');
            //$(this).removeClass('orangeHiperBigButtonBig');
            //$(this).addClass('grayButtonBig');
            $('#formJoin').submit();

    });


    //Desactivate the button JOIN in add.phtml when the user has click
    $('#btnSaveWeb').click(function()
    {
        var registration_terms = $('#registration_terms').is(':checked');

        if (registration_terms == true)
        {
            var product_id = $(this).attr('rel');
            $(this).hide();
            $("#loadingJoinButton").show();
            //$(this).removeClass('orangeHiperBigButtonBig');
            //$(this).addClass('grayButtonBig');
            $('#formJoin').submit();
        }
        else
        {
            $(this).attr('disabled', false);
            $(this).attr('disabled', false);
            $('#joinFlecha').hide();
            $('#joinFlecha').fadeIn();
        }

    });

    $('#errorsDiv').fadeIn('slow');

    $('.closefancy').click(function()
    {
        $.fancybox.close();
    });


    $('#newsForm').ajaxForm(function() {
        subscribeNewsLetter();
    });

    $('#newsFormSp').ajaxForm(function() {
        subscribeNewsLetterSp();
    });
            
    $(".kactoos-reviews").fancybox({
        'titlePosition': 'inside',
        'transitionOut': 'none',
        'padding': 10,
        'margin': 0,
        'centerOnScroll': 'TRUE',
        'scrolling':   'yes'
    });

    $('#htmlSlide').cycle({
        fx:      'scrollHorz',
        timeout:  7000,
        pager:   '#slidePage',
        pagerAnchorBuilder: pagerFactory
    });

    $('.realtimeSlide').cycle({
        fx:     'blindY,blindX',
        timeout:  7000
    });

    $('.productSuggestSlide')
    .after('<div id="navSuggestion">')
    .cycle({
        fx:     'turnRight',
        pager: '#navSuggestion',
        speed:  'fast', 
        timeout:  0
    });
    
    $('.productHomeSlide')
    .after('<div class="clear"></div><div id="navHome">')
    .cycle({
        fx:     'turnRight',
        pager: '#navHome',
        speed:  'fast', 
        timeout:  0
    });
    
    $("#subHeaderCat").click(
        function () {
            var subHeaderCat = $("#subHeaderCat").width();
            var subHeaderBtn = $("#subHeaderBtn").width();
            
            var kactoosMenu = parseInt(subHeaderCat) + parseInt(subHeaderBtn) - parseInt(23);
            
            $("#kactoosMenu").width( kactoosMenu );
            $("#kactoosMenu").width( kactoosMenu );
            
            $("#kactoosMenu").slideToggle();   
            var imgRow = $('#imgRow').attr("src");
            if( imgRow == '/images/layout/menu_header/cat_down_arrow.png' ) {
                $('#imgRow').attr({
                    src: "/images/layout/menu_header/cat_up_arrow.png"
                });
            }else {
                $('#imgRow').attr({
                    src: "/images/layout/menu_header/cat_down_arrow.png"
                });
            }
    });

    $("#loginBoxOpen").click(function(){
        if ( $.browser.msie ) {
          if( $.browser.version <= 7){
              $("#.history").fadeToggle("fast");
              $(".menu").fadeToggle("fast");
          }
        }
        $('#socialNet').toggle();
        $(this).toggleClass("loginBoxHover");
        $("#loginBox").fadeToggle("fast");
    });
    
    $( "#loginBoxOpen" ).click( function( e ) { e.stopPropagation(); } );
    $( "#loginBox" ).click( function( e ) { e.stopPropagation(); } );
    
    $( document ).click( function () {
        $("#loginBox").hide();
        $('#socialNet').show();
        $("#loginBoxOpen").removeClass("loginBoxHover");
    } );
    

    $(".loginBoxOpenRealTime").click(function(){
        
        $('#loginBoxOpen').toggleClass("loginBoxHover");
        $("#loginBox").fadeToggle("fast");
    });

    /*$(".kactoos-messages").fancybox({
        'titlePosition': 'inside',
        'transitionOut': 'none',
        'autoDimensions' : 'TRUE',
        'scrolling'	 : 'no',
        'height' : 500,
        'type'          : 'ajax'
    });*/
    
    $(".kactoos-messages").click( function () {
        /*$.fancybox({
            'titlePosition': 'inside',
            'transitionOut': 'none',
            'autoDimensions' : 'TRUE',
            'scrolling'     : 'no',
            'height'     : 500,
            'type'          : 'ajax',
            'href'       : $(this).attr('href')
        });*/
        sendMessage( $(this).attr('href') );
        return false;
    });

    $(".productNumComments").live('click', function () {
            var id = $(this).attr( "product_country_id" );
            showComments( id, false );
            return false;
        }
    );
    $(".btn_comments").live('click', function () {
            var id = $(this).attr( "product_country_id" );
            var realtimeId = $(this).attr( "realtime_id" );
            showComments( id, realtimeId , false );
            return false;
        }
    );
    $(".realTimeNumComments").live('click', function () {
            var id = $(this).attr( "product_country_id" );
            var realtimeId = $(this).attr( "realtime_id" );
            showComments( id, realtimeId, false );
            return false;
        }
    );
        
    $("#logincheck").click(
        function () {
            $("#superGroupLoginBox").fadeIn();
            $("#generalForm").hide();
            $("#errorsDiv").hide();
        }
    );
        
    $("#registercheck").click(
        function () {
            $("#superGroupLoginBox").hide();
            $("#generalForm").fadeIn();
        }
    );
        
    $(".view_comm").live('click', function() {
            $(".hidecomm").slideToggle("slow");
            $(".boxViewcom").hide("fast");
        }
        );        

});
function emptybox(id_user,layout, section){
     $('#user'+section+'_add_'+id_user).empty();
     if(layout=="list"){
         $('#user'+section+'_add_'+id_user).html("<div style='height:50px;width:134px;float:left;text-align:center;padding:30px 3px 13px;'><br/><img src=/images/load.gif></div>");
     }else{
         $('#user'+section+'_add_'+id_user).html("<div style='height:50px;width:50px;float:left;padding:8px 3px 13px;text-align:center;'><br/><img src=/images/load.gif></div>");
     }
}

function addmini( userId, layout, section ) {
    if ( !layout ) {
        layout = "";
    }
    
    $(".qtip").hide();
    
    $.ajax( {
        before: emptybox( userId, layout, section ),
        url: SERVER_URL + "/social/friends/add/user_id/" + userId + "/layout/" + layout,
        success: function( data ) {
            $( "#user" + section +"_add_" + userId ).empty();
            //$('#user_add_'+id_user).html(data);
            $( "#friends_list" ).load( SERVER_URL + "/social/friends/get-friends" );
            
            if ( data.return_ == true ) {
                $.notifyBar( {
                    html: FRIEND_NOTIFICATION_MESSAGE,
                    delay: 2000,
                    animationSpeed: "normal"
                } );
            } else {
                $.notifyBar( {
                    html: FRIEND_NOTIFICATION_MESSAGE_EXIST,
                    delay: 2000,
                    animationSpeed: "normal"
                } );                
            }
           
            if ( typeof NO_FRIEND_SUGGESTIONS == "undefined" ) {
                return;
            }

            if ( section=="dashboard"){
                if ( $( ".dashboardComunitySuggestions" ) ) {
                    if ( $( ".dashboardComunitySuggestions ul li" ).length == 0 ) {
                        $( ".dashboardComunitySuggestions" ).html( NO_FRIEND_SUGGESTIONS );
                    }
                }
            } else {
                if ( $( "#friendsSuggestions" ) ) {
                    if ( $( "#friendsSuggestions ul li" ).length == 0 ) {                        
                        $( "#friendsSuggestions" ).html( NO_FRIEND_SUGGESTIONS );
                    }
                }
            }
        }
    } );
}

function addFavoriteProduct( productId ) {


    $.ajax( {
        url: SERVER_URL + "/products/index/add-favorite/id/" + productId,
        success: function() {
            $.notifyBar( {
                html: PRODUCT_FAVORITE,
                delay: 2000,
                animationSpeed: "normal"
            } );
        }
    } );
}

function simpleNotification( ) {

    $.notifyBar( {
        html: NOTIFICATION_TXT,
        delay: 3000,
        animationSpeed: "normal"
    } );

}

function pagerFactory(idx, slide) {
    var s = idx > 2 ? ' style="display:none"' : '';
    return '<div id="p'+(idx+1)+'" class="pagesSlide">'+(idx+1)+'</div>';
}


function rollOverLB ( strImgName )
{
    // Turn off all of the images
    $("#step1").attr("src" , $("#step1").attr("src").replace("_on", "_off") );
    $("#step1").attr("style" , "opacity:.5");
    $("#step2").attr("src" , $("#step2").attr("src").replace("_on", "_off") );
    $("#step2").attr("style" , "opacity:.5");
    $("#step3").attr("src" , $("#step3").attr("src").replace("_on", "_off") );
    $("#step3").attr("style" , "opacity:.5");

    // Turn on the current image
    strNewSRC = $("#" + strImgName).attr("src").replace("_off", "_on");
    $("#" + strImgName).attr("src" , strNewSRC );
    $("#" + strImgName).attr("style" , "opacity:1");

    // Tur on the text
    strTextId = strImgName.replace("step", "");

    // Turn off all of the methods, and do it with all the possible ways
    $(".lbIntroText").stop( true, true ).clearQueue().hide();

    $("#lbStep" + strTextId).stop().show();
}

/**
 * Sets a cookie for the overlay stuff, this uses the jquery cookie library :)
 */
function setCookie ( strCookieName, strCookieValue )
{
    var date = new Date();
    date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
    $.cookie( strCookieName , strCookieValue, {
        path: '/',
        expires: date
    });
}


// Categories Menu
var timeout         = 50;
var closetimer		= 0;
var ddmenuitem      = 0;
var ddmenuitemDiv      = 0;

function jsddm_open()
{
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');
    ddmenuitemDiv = $('#kactoosMenu').css('display', 'block');
}

function jsddm_close()
{
    if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
    if(ddmenuitemDiv) ddmenuitemDiv.css('display', 'none');
}

function jsddm_timer()
{
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer()
{
    if(closetimer)

    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

document.onclick = jsddm_close;


// ------------------------------


function subscribeNewsLetter(){
    $.post( "/users/index/subscribe-news", $("#newsForm").serialize(),

        function(html)
        {
            //alert("¡Producto Agregado a tu lista de deseos!");
            $.blockUI({
                message: '<h2 style="font-size: 16px; color: #FFF">'+html+'</h2>',
                css: {
                    border: 'none',
                    padding: '15px',
                    'z-index': '99999',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                }
            });
            setTimeout($.unblockUI, 3000);
        });
}


function subscribeNewsLetterSp(){
    $.post( "/users/index/subscribe-news", $("#newsFormSp").serialize(),

        function(html)
        {
            //alert("¡Producto Agregado a tu lista de deseos!");
            $.blockUI({
                message: '<h2 style="font-size: 16px; color: #FFF">'+html+'</h2>',
                css: {
                    border: 'none',
                    padding: '15px',
                    'z-index': '99999',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                }
            });
            setTimeout($.unblockUI, 3000);
        });
}
	 
	 
function botlink(url) {
	
    $.post(url, "",
		
        function(html)
        {
            //alert("¡Producto Agregado a tu lista de deseos!");
            $.blockUI({
                message: '<h2 style="font-size: 16px; color: #FFF">'+html+'</h2>',
                css: {
                    border: 'none',
                    padding: '15px',
                    'z-index': '99999',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                }
            });
            setTimeout($.unblockUI, 3000);
        });

}



function pulsar(e) {
    tecla = (document.all) ? e.keyCode :e.which;
    return (tecla!=13);
}

function superGroupImg(img) {
    $("#productImg").attr("src" , "http://www.kactoos.com/images/products/"+img );
}


function sendMessage( url ) {
    $.fancybox({
        'width'		        : 300,
        'height'		: 500,
        'autoScale'		: false,
        'transitionIn'		: 'none',
        'transitionOut'		: 'none',
        'type'			: 'ajax',
        'href'			: url
    });
}


function saveProductShare( product, network, user, post_id ){
    if( typeof(product) != 'undefined') {
        $.get( "/products/index/insert-products-share/product/"+product+"/network/"+network+"/user/"+user+"/post_id/"+post_id);
    }
}

