var loading={
    show:function(){
        $('#loading').fadeIn()
    },
    hide:function(){
        $('#loading').hide()
    }
};
var codigo;
var last_chat_msg=0;
var original_title;
var alert_title;
var windowFocus;
var user_id;
var chatWindow=true;
var chatHearbeat=true;

$(document).ready(function(){
    original_title = document.title;
    $([window, document]).blur(function(){
        windowFocus = false;
    }).focus(function(){
        windowFocus = true;
        document.title = original_title;
    //$('#main_chat_window').removeClass('beating');
    //chatHearbeat=true;
    });
});

function submit_contact(form,show){

    $.ajax({
        url:$(form).attr('action'),
        data:'&'+$(form).serialize(),
        type:'POST',
        dataType: 'json',
        beforeSend:function(){
            loading.show();
        },
        error:function(){
            alert('Ocurrió un error enviando su solicitud, por favor intente de nuevo');
            loading.hide();
        },
        success:function(R){
            eval(R.js);
            if(show == undefined) alert(R.html);
            else $(show).html(R.html);

            if(R.error==1 && show != undefined){
            $(show).addClass('error');
            $(show).fadeIn(500).delay(5000).fadeOut(2500);
            }
            if(R.error !=1){
            $(show).addClass('success').removeClass('error');
            $(show).fadeIn(500).delay(800).fadeOut(2500);
            }
            loading.hide();
            }
            });
        return false;
        }

        function ajax(url,show){
        $.ajax({
            url:url,
            type:'GET',
            dataType: 'json',
            beforeSend:function(){
            loading.show();
            },
            error:function(){
            alert('Ocurrió un error enviando su solicitud, por favor intente de nuevo');
            loading.hide();
            },
            success:function(R){
            eval(R.js);
            if(show == undefined) alert(R.html);
            else $(show).html(R.html);
            
        if(R.error==1 && show != undefined){
        $(show).addClass('error');
        }
        if(R.error !=1){
        $(show).addClass('success').removeClass('error');
        }          
        loading.hide();
        }
        });
    return false;
    }
    function load_submenu(el){
        //$('.sidebar').find('');
    
        $(el).addClass('active');
        $(el).parent().find('.submenu').slideToggle('slow');
        }
        function open_pop_product(){
        $('#pop_back').show();
        $('#pop_up').fadeIn(500);

        }
        function close_pop_product(){

        $('#pop_up').fadeOut(200,function()
        {
            $('#pop_back').fadeOut(500);
            })

        }


        /*CHAT FUNCTIONS*/

        function addMessages(xml) {
        if($(xml).find('status').text() == '1'){
        $(xml).find('message').each(function() {
            last_chat_msg = $(this).find('time').text();
            author = $(this).find('author').text();
            if($(this).find("author_id").text() != user_id) $("#messagewindow").append('<sup><a href="javascript:;" onclick="chat_block(\''+ $(this).find("author_id").text() +' \')" title="Block User"> x </a></sup>');
            $("#messagewindow").append('<b>'+$(this).find("author").text()+'</b>: '+$(this).find("text").text()+"<br />");
            });        
        alert_title = author+' says...';
        if(chatHearbeat) heartBeat(1);
        changeTitle();
        $("#messagewindow").scrollTo($('b:last'));
        $("#chat").show();
        }
        }
        function heartBeat(start){
        if(start){
        $('#main_chat_window').addClass('beating');
        chatHearbeat=false;
        }
        if(chatHearbeat==false){
        $('.beating').toggleClass('beat');
        setTimeout("heartBeat()", 800);
        }
        }
        function changeTitle(){
        if(windowFocus != true){
        if(original_title != document.title) document.title = original_title;
        else document.title = alert_title;
    setTimeout('changeTitle()', 1000);
    }
    }
    function loadMsg(recursive) {
    $.ajax({
        url:ajax_uri+"chat_backend/"+last_chat_msg+'/'+user_id,
        dataType:'xml',
        error:function(){
        setTimeout('loadMsg()', 5000);
        },
        success:function(xml) {
        addMessages(xml);
        if(recursive == undefined && chatWindow) setTimeout('loadMsg()', 5000);
        }
        });
    }

    function chat_send(form){
    if($('#msg').val() == ''){
    return false;
    }
    $.ajax({
        url:ajax_uri+"chat_update/"+last_chat_msg+'/'+user_id,
        type:'POST',
        data:'&'+$(form).serialize(),
        beforeSend:function(){
        $("#messagewindow").append("<span class='me'><b>Me</b>: "+$("#msg").val()+"</span>");
        $("#messagewindow").scrollTo($('b:last'));
        $("#msg").val("");
        $("#msg").focus();
        },
        success:function(response) {            
        $(response).find('message').each(function() {
            last_chat_msg = $(this).find('time').text();
            if($(this).find("author_id").text() != user_id) $("#messagewindow").append('<sup><a href="javascript:;" onclick="chat_block(\''+ $(this).find("author_id").text() +' \')" title="Block User"> x </a></sup>');
            $("#messagewindow").append('<b>'+$(this).find("author").text()+'</b>: '+$(this).find("text").text()+"<br />");
            
            $("#messagewindow").scrollTo($('b:last'));
            });
        $("#messagewindow").find('.me').remove();
        }
        });
    return false;
    }
    function closeChat(){
    $('#chat').remove();
    chatWindow = false;
    }
    function offChat(){
    $('#chat').hide();
    chatWindow = false;
    $('.online').replaceWith('<span class="offline" onclick="onChat();">Offline</span>');
    $.post(ajax_uri+'chat_off/'+user_id);
    }
    function onChat(){
    $('#chat').show();
    chatWindow = true;
    loadMsg();
    $('.offline').replaceWith('<span class="online" onclick="offChat();">Online</span>');
    $.post(ajax_uri+'chat_on/'+user_id);
    }
    function initWindow(){    
    $("#msg").focus();
    if(!chatHearbeat){
    $('#main_chat_window').removeClass('beating');
    chatHearbeat=true;
    }
    }
    function chat_block(to_user){
    $.ajax({
        url:ajax_uri+"create_chat_block/"+user_id+'/'+to_user,
        type:'POST',
        dataType: 'json',
        success:function(response) {  
        if(response.wasblocked == 1){
        $('.blocked_user.'+to_user).remove();
        }else{
    $('#blocked').append(response.append);
    $('#blocked').addClass('blocked_list');
}
$("#messagewindow").append(response.msg);
    }
});
}
function request(url,data,show,callback){
    $.ajax({
        url:url,
        type:'POST',
        data: '&'+(data != undefined ? data : ''),
        dataType: 'json',
        success:function(R){
            eval(R.js);
            if(show == undefined) alert(R.html);
            else $(show).html(R.html);
           
            if(R.error==1 && show != undefined){
                $(show).addClass('error');
                $(show).fadeIn(500).delay(5000).fadeOut(2500);
            }
            if(R.success==1){
               
                $('input[name=ped_id]').val(R.ped_id);
                codigo = R.ped_codigo;
                eval(callback);
        //$(show).addClass('success').removeClass('error');
               
                 
                   
        }            
        }
    });
    return false;
}
function up_step_3(){
    $("ul.tabs li").removeClass("active");
    $('.st_3').addClass("active");
    $(".tab_content").hide();
    $('input[name=quantity]').val($('input[name=ped_cantidad]').val());
    var ret = $('input[name=return]').val();
     $('input[name=return]').val(ret + $('input[name=ped_id]').val()+'/'+codigo);
    var activeTab = $('.st_3').find("a").attr("href");
    $(activeTab).fadeIn();
}
function send_cupon(url,data,show,callback){
    $.ajax({
        url:url,
        type:'POST',
        data: '&'+(data != undefined ? data : ''),
        dataType: 'json',
        success:function(R){
            eval(R.js);
            if(show == undefined) alert(R.html);
            else $(show).html(R.html);
           
            if(R.error==1 && show != undefined){
                $(show).addClass('error');
                $(show).fadeIn(500).delay(5000).fadeOut(2500);
            }
            if(R.success==1){
               
                $('input[name=ped_id]').val(R.ped_id);
                var cupon = $('#cupon_form').serializeJSON();
                $.extend(cupon,{
                    cup_pedido: R.ped_id
                });
                $.post($('#cupon_form').attr('action'),cupon,function(){
                eval(callback);    
                });
              
               
        //$(show).addClass('success').removeClass('error');
               
                 
                   
        }            
        }
    });
    return false;
}
/*CHAT FUNCTIONS*/
/*
 * Remove empty spaces from a string (like php trim function)
 */
function trim(text) {
    text= text.replace(/ /g,""); //elimina espacios a izquierda y derecha
    text= text.replace(/\n\r/g,"");
    text= text.replace(/\n/g,"");
    return text;
}
function video_refresh(link,where,w,h){
    if(trim(link)!=''){
        $(where).html('');
        $(where).append('<p id="message_flash">Please install the Flash Plugin</p>');
        var flashvars = {
            file:link,
            autostart:'false',
            screencolor:'#333333'
        };
        var params = {
            allowfullscreen:'true',
            allowscriptaccess:'always',
            wmode: 'transparent'
        };
        var attributes = {
            id:'player1',
            name:'player1'
        };

        if(w == undefined || h == undefined){
            swfobject.embedSWF('plugins/mediaplayer/player.swf','message_flash','480','270','9.0.115','false',flashvars, params, attributes);
        }else{
            swfobject.embedSWF('plugins/mediaplayer/player.swf','message_flash',w,h,'9.0.115','false',flashvars, params, attributes);
        }
    }
}
(function( $ ){
    $.fn.serializeJSON=function() {
        var json = {};
        jQuery.map($(this).serializeArray(), function(n, i){
            json[n['name']] = n['value'];
        });
        return json;
    };
})( jQuery );
