/* -------------------------------- */
/* General JS File for Shoppy.es    */
/* Author: HTMLOn.com Dev Team      */
/* -------------------------------- */

function dump(obj)
{
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

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

// Converts any string to slug string
// All string lowercase
// Spaces => dashes.
// Example: Input: Htmlon DEV Team
//          Output: htmlon-dev-team
function str2slug(str) {

      str = str.replace(/^\s+|\s+$/g, ''); // trim
      str = str.toLowerCase();

      // remove accents, swap ñ for n, etc
      var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
      var to   = "aaaaeeeeiiiioooouuuunc------";
      for (var i=0, l=from.length ; i<l ; i++) {
        str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
      }

      str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
        .replace(/\s+/g, '-') // collapse whitespace and replace by -
        .replace(/-+/g, '-'); // collapse dashes

      return str;

}

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

function apply_closable() {

    // Puts button.
    $('.closable').prepend('<div class="closable-button"></div>');

    // Click Trigger.
    $('.closable .closable-button').click(function() {
	$(this).parent().fadeOut();
    });
}

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

function apply_blinks() {

    $('.blink_red2white').animate({ backgroundColor: 'pink' },1000).animate({ backgroundColor: '#fff' },2000);
    $('.blink_red2yellow').animate({ backgroundColor: 'pink' },1000).animate({ backgroundColor: '#fffbcc' },2000);
    $('.blink_green2white').animate({ backgroundColor: '#d3ff75' },1000).animate({ backgroundColor: '#fff' },2000);

}

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

function apply_text_counter()
{
    $('.text_counter').keypress(function() {

            text_counter = $(this).attr('value').length;
            max_counter = parseInt($(this).attr('rel'));

            // If color != red
            if ($(this).css('color')!='rgb(255, 0, 0)')
            {
                // Stores old color
                $(this).data('old_text_color',$(this).css('color'));
            }

            if (text_counter >= max_counter)
            {
                $(this).css('color','red').css('background-color','pink');
            }
            else
            {
                $(this).css('color',$(this).data('old_text_color')).css('background-color','white');
            }

    });

    // Fires on init.
    $('.text_counter').trigger('keypress');

}

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

function apply_required_fields()
{
    $('input.required').after('<span class="required">*</span>');
}

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

function datetounix(datestr)
{
    // Supose date is always spanish format.
    var datesplit = datestr.split('/');
    datestr = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
    return Math.round(Date.parse(datestr)/1000.0);

}

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

function unixtodate(timestamp,lang)
{

    if (lang==null || lang=='undefined' || lang=='') { lang='es' }
    if (timestamp==null || timestamp=='undefined' || timestamp=='' || timestamp==0) { return ""; }
    var date = new Date(timestamp*1000);
    var _mes=date.getMonth()+1;
    var _dia=date.getDate();
    var _anyo=date.getFullYear();
    var _hora=date.getHours();
    var _min=date.getMinutes();
   
    if (_mes<10) { _mes = '0'+_mes; }
    if (_dia<10) { _dia = '0'+_dia; }
    if (_hora<10) { _hora = '0'+_hora; }
    if (_min<10) { _min = '0'+_min; }

    if (lang=='es') {
        return _dia + '/' + _mes + '/' + _anyo + ' ' + _hora + ':' + _min;
    } else {
        return _anyo + '/' + _mes + '/' + _dia + ' ' + _hora + ':' + _min;
    }
   
}

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

function apply_search_field()
{
        var txt_search_product = 'Buscar Producto, Marca, Empresa...';

        $("#searchfield").focus(function (e) {
                if($("#searchfield").attr("value")==txt_search_product) {
                        $("#searchfield").attr("value","");
                }
        });

        $("#searchfield").bind("blur", function (e) {
                        if ($("#searchfield").attr("value")=="") {
                                $("#searchfield").attr("value",txt_search_product);
                        }
        });

        $("#searchfield").keyup(function(e) {

                        if(e.keyCode == 13) {

                                alert("Buscando");

                        }
        });


        $("#searchfield").attr("value",txt_search_product);

}

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

function apply_fancybox() {

        $('a.fancybox').fancybox({
            'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	300,
		'speedOut'		:	200,
		'overlayShow'	:	true
        });

        $('a.imagezoom').fancybox({
            'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	300,
		'speedOut'		:	200,
		'overlayShow'	:	true

        });

}
//------------------------------------------------------------------------------

function apply_zoomers() {
    
    // On Hover put Magnify Glass over Image and process inputs.
        $('#image-zoom').remove();

        $('a.imagezoom').hover(function() {
           imageMatch = $(this).children('img');
           imageMatch.after('<img id="image-zoom" src="/rsc/v1/img/interface/image-zoom.png" width="55" height="55" alt="Zoom" style="position:absolute; cursor:pointer; display:none;" />');
           imagePosition = imageMatch.position();
           imageSize_X = parseInt((imagePosition.left + imageMatch.width() / 2)-($('#image-zoom').width() / 2));
           imageSize_Y = parseInt((imagePosition.top + imageMatch.height() / 2)-($('#image-zoom').height() / 2));
           $('#image-zoom').css({ top: imageSize_Y, left: imageSize_X });

           $('#image-zoom').fadeIn('fast');
        },function(){
            $('#image-zoom').remove();
        });
    
}

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

function apply_timers()
{

        $(".countdown_timer").countdown({
                source: 'title'
                ,txtAfterDays:' Días '
                ,txtAfterHours:'h '
                ,txtAfterMinutes:'m '
                ,txtAfterSeconds:'s'
                ,onExpires: function(obj) {
                    $(obj).html('&iexcl;Tiempo Finalizado!');
                }
        });
}

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


function vote_coupon(obj,idcoupon,type,message,color)
{
    
    if ((color=="") || (color=="undefined") || (color==null)) {
        color="658d2c";
    }

    $.ajax({

        url:"/cupones/votar"
       ,data:"id_coupon=" + idcoupon + "&type=" + type
       ,type: "POST"
       ,success: function() {
           if ((message=="") || (message=="undefined") || (message==null)) {
             message = "&iexcl;Gracias por ayudar!";
           }
       }
       ,error: function() {
           message = "Se produjo un error.";
       }

    });

    // Show message

    $(obj).parent().fadeOut(500,function() {
                $(obj).parent().html('<span style="color:' + color + ' ; font-weight:bold;">' + message + '</span>');
           });
    $(obj).parent().fadeIn(500);


}

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

function prepare_common_events() {

    // Banner Share On_Click
    $("#div_banner_share").click(function() {
        $(this).fadeOut(200,function() {
            $("#div_banner_share_buttons").fadeIn(200);
        });
    });
    
    // Box Subscription
    
    if ($("#email_subscription").length>0) {
    
         $("#email_subscription").keyup(function(e) {	
                if(e.keyCode == 13) {
                    window.location=$('#send_subscription').attr('href');
                }
            });
        
    }
    
    // Email Field Type
    
    if ($(".email_field").length>0) {
                
       
        if ($(".email_field").attr("value")=="") {
            $(".email_field").attr("value",'Escribe tu e-mail...').css("color","#999");
        }
        
        $(".email_field").focus(function() {
            if ($(this).attr("value") == 'Escribe tu e-mail...') {
                $(this).attr("value","").css("color","#000");
            }
        });
        
        $(".email_field").blur(function() {
            if ($('.email_field').attr("value") == '') {
                $('.email_field').attr("value","Escribe tu e-mail...").css("color","#999");
            }
        });
        
    }
    
}

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

 function offer_image_gallery_switch(obj_img) {
        
        $("a#big_image_offer").attr("href",$(obj_img).attr("rel"));
        $("a#big_image_offer img").attr("src",$(obj_img).attr("id"));
    }

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

  function subscribe_email(obj) {
      
      obj_name = "#" + obj;      

      if ($(obj_name).length>0) {
      
            // Prepare Ajax UI.
            $(obj_name).block({
                   message: '<div style="width:150px; height:75px; border:3px solid #ccc; padding-top:20px; background:#fff; text-align:center; color:#777;"><img src="/rsc/v1/img/preloaders/circular.gif" /><br />Enviando...</div>'
                   ,css: { border:0, width:150, background:"transparent" }
                   ,overlayCSS: { opacity:0.4, background:"#003c7f" }
                   ,fadeIn: 150
            });
                        
            // Recopile Data.
            
            str_email = $(obj_name + " #email_subscription").attr("value");
            str_type  = $(obj_name + " #type_subscription").attr("value");
            str_id    = $(obj_name + " #id_subscription").attr("value");
                    

            // Error Data
            
            success=false;
            message_ok_email='<span style="padding:10px; color:#4d8522; font-weight:bold; font-size:16px;">&iexcl;Te has suscrito correctamente! <br />&nbsp;&nbsp; Hemos enviado un e-mail para verificar tu suscripción.</span>';
            message_ok_no_email='<span style="padding:10px; color:#4d8522; font-weight:bold; font-size:16px;">&iexcl;Te has suscrito correctamente!</span>';
            message_fail='&iexcl;Se produjo un error, vuélvelo a intentar!';
            message_email_format='&iexcl;La dirección Email es inválida!';
            message_email_exists='&iexcl;Esta dirección Email ya está suscrita en esta zona!';
            message = message_ok_no_email; // By default

            // Send Data.          

             $.ajax({
                url:"/suscripcion/alta"
               ,data:"str_email=" + str_email + "&str_type=" + str_type + "&str_id=" + str_id
               ,type: "POST"
               ,dataType: "text"
               ,async: false
               ,cache: false
               ,success: function(msg) {
                   switch(msg) {
                       
                       case "OK_WITH_VALIDATION":
                           message = message_ok_email;
                           success=true;
                           $(obj_name + " #number_subscribers").html( parseInt($(obj_name + " #number_subscribers").html()) + 1 );
                           break;
                       case "OK_WITHOUT_VALIDATION":
                           message = message_ok_no_email;
                           success=true;
                           $(obj_name + " #number_subscribers").html( parseInt($(obj_name + " #number_subscribers").html()) + 1 );
                           break;
                       case "ERROR_MAIL":
                           message = message_email_format;
                           success=false;
                           break;
                       case "ERROR_EXISTS":
                           message = message_email_exists;
                           success=false;
                           break;
                       default:
                           message = message_fail;
                           success=false;
                   }

               }
               ,error: function() {
                   message = message_fail;                  
                   success=false;
                   
               }
               
            });
            
            if (success) { 
               $(obj_name + " #subscription_controls").html(message);
               $(obj_name + " #subscription_errors").hide();
            } else {
               $(obj_name + " #subscription_errors").html(message);
            }
            
            // Unblock
            $(obj_name).unblock({
                      fadeOut:150
            });
             
      }
  }

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

function apply_box_offers() {
 
     // Box Offers
    if ($('.offer_row').length>0) {
		
        // Offer expired.
        $('.offer_row_expired').unbind().block({
                   message: ''
                   ,css: { cursor:'normal', border:0, width:150, background:"transparent" }
                    ,overlayCSS: { cursor:'normal' , opacity:0.15, background:'#900 url(/rsc/v1/img/interface/bg_offer_row_expired.png)' }
                   ,fadeIn: 0

               });
        
        
    }

}

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

function apply_tabs() {

	$(".tab_content").hide(); //Hide all content
        
        if (window.location.hash) {
            $("ul.tabs li a[href$='" + window.location.hash + "']").parent().addClass("active").show();
            $("div" + window.location.hash + ".tab_content").show();
        } else {
            $("ul.tabs li:first").addClass("active").show();
            $(".tab_content:first").show();
        }
    
        	
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active");
		$(this).addClass("active");
		$(".tab_content").hide();

		var activeTab = $(this).find("a").attr("href");
		$(activeTab).fadeIn();
		return false;
	});

}

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

function offer_report_wrong(id,slug)
{
    
      $.ajax({
            url:"/ofertas/ajax_comprobar_oferta"
           ,data:"id_offer=" + id + "&slug=" + slug
           ,type: "POST"
           ,cache: false
           ,dataType: 'text'
           ,async: false
           ,success: function() {      
               $('#report_wrong_offer').html('La oferta ha sido reportada a los administradores de Shoppy. &iexcl;Gracias!');
               $('#report_wrong_offer').attr('href','javascript:alert("Esta oferta ya ha sido reportada como invalida.");');
           }
           ,error: function(msg) {
               $('#report_wrong_offer').html("Se produjo un error al reportar.").css("color","#900");
              
           }

       });
}

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

// -------------------
// --- ON DOM INIT ---
// -------------------

$(function() {

   apply_closable();
   apply_blinks();
   apply_text_counter();
   apply_required_fields();
   apply_search_field();
   apply_fancybox();
   apply_zoomers();
   apply_timers();
   apply_tabs();
   apply_box_offers();
   prepare_common_events();

});
