$(document).ready(function($){
     if(c==0)
     {  
        //if ($("#headlineWrapper").length) { 
//            $('#headlineWrapper').uBillboard({
//                speed: 900,                         // animation duration (in miliseconds)
//                delay: 6000,                        // delay between animations (in miliseconds)
//                width: '595px',                        // container width
//                height: '250px',                    // container height
//                effect: 'cycle',                    // Transition effect: cycle | random | horizontal | vertical | async
//                square_resolution: 100,                // resolution of one transition square in pixels
//                load_check_interval: 110            // how ofted do we poll for image load completion
//                
//            });
//        }
     }
     else
     { 
        if ($(".rdest").length) { 
            $('.rdest').uBillboard({
                speed: 900,                         // animation duration (in miliseconds)
                delay: 6000,                        // delay between animations (in miliseconds)
                width: '595px',                        // container width
                height: '395px',                    // container height
                effect: 'cycle',                    // Transition effect: cycle | random | horizontal | vertical | async
                square_resolution: 100,                // resolution of one transition square in pixels
                load_check_interval: 110            // how ofted do we poll for image load completion
                
            });
        }
     }
     
     //if ($("#newWrapper").length) { 
//        $('#newWrapper').uBillboard({
//            speed: 900,                         // animation duration (in miliseconds)
//            delay: 6000,                        // delay between animations (in miliseconds)
//            width: '160px',                        // container width
//            height: '129px',                    // container height
//            effect: 'cycle',                    // Transition effect: cycle | random | horizontal | vertical | async
//            square_resolution: 60,                // resolution of one transition square in pixels
//            load_check_interval: 110            // how ofted do we poll for image load completion
//            
//        });
//    }
     
        
    if ($("ul#nav").length) {         
       $("ul#nav").tabs("div.panes > div.pan");
       $("ul.ui-tabs-nav").tabs("div.hlines > div.ui-tabs-panel", {rotate: true}).slideshow({interval: 6000});
       $("ul.ui-tabs-nav").data("slideshow").play(); 7
    }
        
    var options = {
        zoomWidth: 265,
        zoomHeight: 265,
        showEffect:'show',
        hideEffect:'fadeout',
        fadeoutSpeed: 'slow',
        title :false,
        xOffset: 10,
        yOffset: 0,                 
        position: "right" //and MORE OPTIONS
    }; 
    $(".jqzoom").jqzoom(options);     
    
    //Suscripcion a Newsletter
    $('#btnNewsSusc').click(function() { 
        if($("#machine").val()=="" && is_email($("#news_mail").val()))
        {
            $.ajax({
                url: "registrar_suscriptor.php",
                global: false,
                type: "GET",
                data: ({
                    ran : Math.random(),
                    email : $("#news_mail").val()
                }),
                dataType: "html", 
                success: function(transport){
                    suscripcion_newsletter_correcta();
                }
            }) ;
        }
        else
        {
            alert("Ingresa correctamente tu mail");
            $("news_mail").focus();
        }    
    });
    
    $('#suscripcion_news_msg').click(function() { 
        $('#suscripcion_news_msg').fadeOut();
    });
    
    $("a[rel^='prettyPhoto']").prettyPhoto(); 
    $("a[rel^='articuloPhoto']").prettyPhoto();
    
    $('#emitir_pedido').click(function() { 
        emitir_pedido();
    });
    
    $('#cancelar_pedido').click(function() { 
        cancelar_pedido();
    });
    
    $("#terminosycondiciones").fancybox({
         'width' : '90%',
         'height' : '90%',
         'autoScale' : false,
         'transitionIn' : 'none',
         'transitionOut' : 'none',
         'type' : 'iframe'
    });
    
    $("a[rel^='productoPhoto']").prettyPhoto();
    
});


function is_email(email)
{        
    if(email != 0)
    {
        if(isValidEmailAddress(email))
        {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function isValidEmailAddress(emailAddress) {
     var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
     return pattern.test(emailAddress);
}

function suscripcion_newsletter_correcta()
{
    $('#suscripcion_news_msg').fadeIn();//css({'display': '', 'visibility':'visible'});
}

//Autosuggest
var r;
var q;
var id;
var src;

function autosuggest(search, results, value_id, accion)
{
    r = $(results);
    q = $(search);
    id = $(value_id);
    src = search;
    
    $.ajax({
        url: "lib/search.php",
        global: false,
        type: "GET",
        data: ({
            q: q.val(),
            i:value_id,
            a:accion,
            ran:Math.random()
        }),
        dataType: "html", 
        success: function(transport){
            r.html(transport).css({'display':'block', 'z-index':'9998'});
        }
    }) ;
}

function autosuggest_select(valor, nombre)
{
    id.val() = valor;
    $(src).val() = nombre;
    r.fadeOut();
}

function executeLogin()
{              
    if($("#login_name").val()!="" && $("#login_pass").val()!="")
    {
        $.ajax({
            url: "content/login.php",
            global: false,
            type: "GET",
            data: ({
                email: hex_md5($("#login_name").val()),
                pass:  hex_md5($("#login_pass").val()),
                ran: Math.random()                                         
            }),
            dataType: "html", 
            success: function(transport){
                if(transport != 0)
                {                        
                    window.location = "index.php?c=micuenta";
                }
                else
                {
                    alert("El E-mail/Usuario o Contraseña son incorrectos!");
                }
            },
            error: function(){
                alert('¡Ocurrio un error al intentar loguearse! ' +transport);
              }

        }) ;
    }
    else
    {
        alert("Ud. debe completar todos los campos!");
    }
}


/*
* Mayoristas
*/

function subrubros(rubro_id)
{   
    $.ajax({
        url: "common/subrubros.php",
        global: false,
        type: "GET",
        data: ({
            rubro_id : rubro_id,
            form : 0,
            ran: Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
              $("#subrubros").html = transport;
        },
        error: function(){
            alert("Ocurrio un error al interntar cargar los Sub Rubros");
        }
    }) ;
}

var limit_old = 1;
function buscar_productos(limit,opcion,callBack)
{
    limit_old = limit;
    
    $("#resultados").html("<img src='contextus/images/indicator.gif'/>");
    
    var clave = "";
    if($("#qm").val()!="BUSCAR")
    {
        clave = $("#qm").val();   
    }
    
    $.ajax({
        url: "common/productos_buscar.php",
        global: false,
        type: "GET",
        data: ({
            q : clave,
            opcion : opcion,
            rubro_id : $("#rubro_id").val(),
            subrubro_id:$("#subrubro_id").val(),
            l : limit,
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            //alert(transport);
            $("#resultados").html(transport);
            $("#contenido").val(transport);
            
            if (typeof callBack == 'function'){
                callBack.call();
              }

        },
        error: function(){
            alert("Error en el filtrado!");    
        }
    }) ;
}

function print_lista() {
    buscar_productos('1','lista', function(){
        $("#frm_print").submit();
    });
    
    
}

//Buscar Clientes
function buscar_clientes()
{
    $("#micliente").html("<img src='contextus/images/indicator.gif'/>");
    
    var clave = "";
    if($("#qc").val()!="DNI / CUIT / EMAIL / RUC" && $("#qc").val()!="")
    {
        clave = $("#qc").val();   
    }    
        
    $.ajax({
        url: "common/clientes_buscar.php",
        global: false,
        type: "GET",
        data: ({
            q : clave, 
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            if(transport!="")
            {
                $("#micliente").html(transport);
                //$("#presupuesto").css({'display':''});
                habilitar_pedido();   
            }
            else
            {
                alert("No existe un cliente con esos datos, intente nuevamente!");
            }
            
        },
        error: function(){
            alert("Error en el filtrado!");    
        }
    }) ;
}

///Carrito
function qty_add(n, prod_id, min)
{
    var actual = parseInt($("#quantity_"+prod_id).val());
    var nuevo = 1;
    if(actual == min && n == -1)
    {
        nuevo = min;
    }
    
    if(actual > min && n == -1)
    {
        nuevo = actual - 1;
    }
    
    if(n == 1)
    {
        nuevo = actual + 1;
    }
    
    $("#quantity_"+prod_id).val(nuevo); 
}

function qty_ver(prod_id)
{
    var actual = parseInt($("#quantity_"+prod_id).val());  
    if(actual < 1)
    {
        $("#quantity_"+prod_id).val(1);   
    }   
}

function agregar_may(producto_id, rango_id, stock)
{
    $("#mipedido").html("<img src='contextus_new/images/indicator.gif'/>"); 
     
    $.ajax({
        url: "ecommerce.php",
        global: false,
        type: "GET",
        data: ({
            p: producto_id,
            rango_id: rango_id,
            may_agr: 1,
            qty: $("#quantity_"+rango_id).val(),
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            //g.info("¡Ud agrego con exito el producto en el Pedido!", {header: "Agregar al Pedido:", life: 6, location: "bl"});
            listar_pedido_mayorista(); 
        },
        error: function(){
            //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10}); 
            alert("¡Ocurrio un error!");    
        }
    }) ;   
}

function update_may(vars)
{    
    $("#mipedido").html("<img src='contextus_new/images/indicator.gif'/>"); 
   
    $.ajax({
        url: "ecommerce.php",
        global: false,
        type: "POST",
        data: vars,
        dataType: "html", 
        success: function(transport){
            //g.info("¡Ud actualizo con exito el producto en el Pedido!", {header: "Actualización del Pedido:", life: 6, location: "bl"}); 
            listar_pedido_mayorista();   
        },
        error: function(){
            //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10});     
            alert("¡Ocurrio un error!" + transport);    
        }
    }) ;
    
}

function delete_may(producto_id, rango_id)
{
    $("#mipedido").html("<img src='contextus_new/images/indicator.gif'/>"); 
    
    $.ajax({
        url: "ecommerce.php",
        global: false,
        type: "GET",
        data: ({
            p: producto_id,
            rango_id: rango_id,
            may_del: 1,
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            //g.info("¡Ud elimino con exito el producto en el Pedido!", {header: "Eliminar del Pedido:", life: 6, location: "bl"}); 
            listar_pedido_mayorista(); 
        },
        error: function(){
            //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10}); 
            alert("¡Ocurrio un error!" + transport);    
        }
    }) ;      
}

function replace_html(el, html) {
    if( el ) {
            var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
            var newEl = document.createElement(oldEl.nodeName);

            // Preserve any properties we care about (id and class in this example)
            newEl.id = oldEl.id;
            newEl.className = oldEl.className;

            //set the new HTML and insert back into the DOM
            newEl.innerHTML = html;
            if(oldEl.parentNode)
                oldEl.parentNode.replaceChild(newEl, oldEl);
            else
            oldEl.innerHTML = html;

            //return a reference to the new element in case we need it
            return newEl;
    }
};

function listar_pedido_mayorista()
{
    $.ajax({
        url: "common/pedido.mayorista.listar.php",
        global: false,
        type: "GET",
        data: ({            
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            //alert(transport);
            //replace_html($("#mipedido"), transport);            
            $("#mipedido").html(transport);
            may_totales();
            //habilitar_pedido(); 
        },
        error: function(){
            //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10}); 
            //alert("¡Ocurrio un error!" + transport);    
        }
    }) ;    
}

function may_totales()
{
    $.ajax({
        url: "common/pedido.mayorista.totales.php",
        global: false,
        type: "GET",
        data: ({            
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            var v = new Array(); 
            v = transport.split(" ");
            
            $("#subtotal").html(v[0]);
            $("#dtopct").html(v[1]);
            $("#dto").html(v[2]);
            $("#total").html(v[3]); 
        },
        error: function(){
            //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10}); 
            //alert("¡Ocurrio un error!" + transport);    
        }
    }) ;        
}

function emitir_pedido()
{
    if($("#total").html()!="0.00")
    {
        //alert($("#cliente_id").val());
        var resp = confirm("Ud. esta por emitir el pedido.\n¿Está seguro?");
        if(resp)
        {
            $("#proceso-pedido").fadeIn();  
            $("#proceso").html("<img src='contextus/images/indicator.gif'/>"); 
             
            var url = "common/pedido.mayorista.guardar.php";
            var vars = "vendedor_asociado_id="+$("#vendedor_asociado_id").val()+"&cliente_id="+$("#cliente_id").val()+"&vendedor_id="+$("#vendedor_id").val()+"&comment="+escape($("#txtComentarios").val())+"&ran="+Math.random();
            
            $.ajax({
                url: "common/pedido.mayorista.guardar.php",
                global: false,
                type: "POST",
                data: vars,
                dataType: "html", 
                success: function(transport){
                    $("#proceso").html("<b>Pedido emitido con exito</b>"); 
                    window.location = 'index.php?c=micuenta&o=sho'; 
                },
                error: function(){
                    //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10}); 
                    //alert("¡Ocurrio un error!" + transport);    
                }
            }) ;
        }
    }
    else
    {
        alert("Ud. debe agregar items en el pedido");
    }
}

function cancelar_pedido()
{
    var resp = confirm("¿Está seguro que desea cancelar el Pedido?");
    if(resp)
    {        
        window.location = "index.php?c=micuenta&pc=1";
    }    
}

function listar_mispedidos()
{
    $("#mispedidos").html("<img src='contextus/images/indicator.gif'/>"); 
    
    $.ajax({
        url: "common/pedido.mayorista.mispedidos.php",
        global: false,
        type: "GET",
        data: ({            
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            $("#mispedidos").html(transport);
             
        },
        error: function(){
            //g.warn("¡Ocurrio un error!<br/>"+transport.responseText, {life: 10}); 
            //alert("¡Ocurrio un error!" + transport);    
        }
    }) ;            
}

function habilitar_pedido()
{
    $("#mostrar").fadeIn();
}

/*FindUs*/

function findUs()
{
    $("#findUs").fadeIn();
    initialize();
    search_localizaciones($("#fu_code").val());
}
function findUs_s()
{
    search_localizaciones($("#post-code-s").val());
}

function search_localizaciones(code)
{
    $("#map-results").html("<img src='contextus_new/images/indicator.gif'/>"); 
    
    $.ajax({
        url: "content/findus.php",
        global: false,
        type: "GET",
        data: ({
            code : code,            
            ran : Math.random()                                         
        }),
        dataType: "html", 
        success: function(transport){
            
            var array = transport.split("....");            
            codeAddress(array[0]+" ARGENTINA") ;
            $("#map-results").html(array[0]+" ARGENTINA"); 
            var locations = array[1].split(";;;");
            addMarkers(locations); 
        },
        error: function(){

        }
    }) ;
}

var map;
var infowindow;
var markersArray = [];
var image = 'images/flag2.png';
var image_st = 'images/flag1.png';

function initialize() {      
    $("#map_canvas").css({'width':'920px', 'height':'450px'});
    
    var myLatlng = new google.maps.LatLng(-38.416097, -63.616672);
    
    var myOptions = {
        zoom: 10,
        center: new google.maps.LatLng(-31.3781431,-64.1821276),
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            position: google.maps.ControlPosition.TOP},
        navigationControl: true,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.ZOOM_PAN,
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        scaleControl: true,
        scaleControlOptions: {
            position: google.maps.ControlPosition.BOTTOM_RIGHT
        }, 
        mapTypeId: google.maps.MapTypeId.ROADMAP                  
    }
    
    map = new google.maps.Map($("#map_canvas").get(0), myOptions);
    geocoder = new google.maps.Geocoder();   
    infoWindow = new google.maps.InfoWindow();
}

   
function addMarkers(locations) {
    var companyMarker=[];
    var infowindow=[];
    var loc=null;
    var myLatLng=null;
    
    for(var i = 0; i < locations.length; i++)
    {
        loc = locations[i].split(",,,");
        myLatLng = new google.maps.LatLng(loc[2], loc[3]);
            
            eval("var companyMarker"+i+" = new google.maps.Marker({position:myLatLng,map: map, icon: "+loc[4]+", title:loc[0],zIndex: i});");
        }
        var a=[];
        for(i=0;i< locations.length; i++){

        google.maps.event.addListener(eval("companyMarker"+i), 'click', function() {
            var ind = $(this).attr('z-index');
            if (infowindow[ind]) infowindow[ind].close();
            var loc2 = locations[ind].split(",,,");
            eval("var infowindow"+ind+" = new google.maps.InfoWindow({content: loc2[1]});");
            eval("infowindow"+ind).open(map, eval("companyMarker"+ind));
        });
    }  
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

var geocoder;
  var cliente_id;
  var loc;

  function codeAddress(address) {
    //var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(12);
        
      } else {
 
      }
    });
  }
  
  
//Recomendar a un amigo
function recomendar(prod_id)
{
    $("#recommendUs").fadeIn();
    $("#rec_prod_id").val(prod_id);
}

function recommend_send()
{
    $("#rec-footer").html("<img src='contextus_new/images/indicator.gif'/>"); 
    
    $.ajax({
        url: "content/recommendus.php",
        global: false,
        type: "POST",
        data: ({
            tomail : $("#at_to").val(),            
            frommail : $("#at_from").val(),
            fromname : $("#at_namefrom").val(),
            note: $("#at_msg").val(),
            prod_id: $("#rec_prod_id").val()            
        }),
        dataType: "html", 
        success: function(transport){
            $("#rec-footer").html(transport); 
        },
        error: function(){

        }
    }) ;   
}

//Recomendar a un amigo
function enviarmeproducto(prod_id)
{
    $("#sendproductUs").fadeIn();
    $("#send_prod_id").val(prod_id);
}

function enviarmeproducto_send()
{
    $("#sendproduct-footer").html("<img src='contextus_new/images/indicator.gif'/>"); 
    
    $.ajax({
        url: "content/sendproductus.php",
        global: false,
        type: "POST",
        data: ({
            tomail : $("#send_to").val(),            
            prod_id: $("#rec_prod_id").val()            
        }),
        dataType: "html", 
        success: function(transport){
            $("#sendproduct-footer").html(transport); 
        },
        error: function(){

        }
    }) ;   
}
