var translations = '';
var newCountryCode = '';
var countryCode = 'ES';

$().ready(function() {

/*    if(jQuery('html')[0].lang.substr(0,2)=="es") {
        var banner = $('<a href="http://www.paypal-promo.es/navidad/paypal" target="_blank"><img src="/st/img/paypal_es_120X600.gif" alt="paypal_es_120X600" style="position:absolute; top:30px; right:-130px;" /></a>');
        $('body.home #page').css('position','relative').append(banner);
        banner.click(function(e) {
            window.open('http://www.paypal-promo.es/navidad/paypal','Paypal_promo','width=900,height=700');
            e.preventDefault();
        });
    }
*/
    if(typeof $.cookie("Voucher") != 'undefined') {
        $("#GreenBar").slideDown("slow");
    }

    
    $('#search_form').submit(function (){
        if($('#q').val()!='') document.location.href='/s/'+$('#q').val();
        else document.location.href='/s/e.g. roses';
        return false;
    });

    $('.menu-item-container').hover(function() {
        $(this).children('.menu-item').css('background', '#9cc020');
        $(this).children('.submenu').stop(true, true).slideDown(200);
    }, function() {
        $(this).children('.menu-item').css('background', 'transparent');
        $(this).children('.submenu').slideUp(200);
    });
    $(".lbox").loginbox();
    $('#countryChange').change (function (){
        redirect ('http://' + $(this).val());
    });

    $('#currencyChange').change (function (){
        $.ajax({url: "/ajaxrequest/changecurrency", type: 'post', data: "currency=" + $(this).val(), async: false, success: function(){
            redirect ($(location).attr('href'));
        }});
    });

    $('#deliveryCountryChange').change (function (){
	if($(this).val()!='') {
            var available = true;
            var pc = '';
      	    if ($('#available_delivery_countries').length) {
      	    	available = false;
      	    	available_countries = $('#available_delivery_countries').val();
      	    	ac = available_countries.split(',');
      	    	dc = $(this).val();
                pc = "&promotion_country=" + ac[0];
      	    	for(i in ac) {
      	    	    if ($.trim(ac[i]) == dc) {
      	    	        available = true;
      	    	    }
      	    	}
      	    }

            $.ajax({url: "/ajaxrequest/changedeliverycountry", type: 'post', data: "delivery_country=" + $(this).val() + "&available=" + available + pc, async: false, success: function(data){
		if ((data != '') && (available == false)) {
                    var Rdata = eval('(' + data+ ')');
                    alert(Rdata.msg);
                    redirect (Rdata.url);
	        } else {
		    redirect ($(location).attr('href'));
		}
            }});
        }
     });

     $("#browsing_sort").change (function (){
          var re = new RegExp('\/[0-9]+|\/low|\/high', "g");
          var url = document.location.href.replace(re,'');
          url = url.split("?");
          var newval="";
          if($("#browsing_sort").val() != "") newval = "/"+$("#browsing_sort").val();
          if(url.length==1) { 
              redirect (url[0]+newval);
          } else {
              redirect (url[0]+newval+"?"+url[1]);
          } 
     });

     $(".fq_img").click(function (){
            redirect ($(this).parent().children(".fq_link").attr("href"));
     });

     $(".catalog-product-image").click(function (){
            redirect ($(this).parent().children(".catalog-product-name").children("a").attr("href"));
     });

     $(".catalog-product-buynow").click(function (){
            redirect ($(this).parent().children(".catalog-product-name").children("a").attr("href"));
     });

     $(".catalog-product-desc").click(function (){
            redirect ($(this).parent().children(".catalog-product-name").children("a").attr("href"));
     });
     
     $(".catalog-product-price").click(function (){
            redirect ($(this).parent().children(".catalog-product-name").children("a").attr("href"));
     });
     
     $("span[class$='_text']").click(function (){
         redirect ($('#'+$(this).attr('class').replace('_text','_link')).attr("href"));
     });

     $("#geo-favorite").click(function (){
         redirect ($(this).find(".catalog-product-buynow:eq(0)").children("a").attr("href"));
     });


    $('.suggest').blur(function (){
        if ($(this).val() == ''){
            $(this).val($(this).attr("title"));
            $(this).css('color', '#AAA');
        }
    });
    
    $('.suggest').focus(function (){
        $(this).css('color', 'black');
        if ($.trim($(this).val()) == $.trim($(this).attr("title"))){
            $(this).val('');
        }
    });

    $('#bd_newsletter_c').click (function (){
       $('#bd_newsletter_c2').show();
       $('#bd_newsletter_c').hide();
    });

    $('#email_newsletter').click (function (){
        if ($('#email_newsletter').val() == t('catalog.email')){
            $('#email_newsletter').val('');
        }
    });
    
    $('#footer-newsletter-email').click(function(){
        if ($('#footer-newsletter-email').val() == t('catalog.email')){
            $('#footer-newsletter-email').val('');
        }
    })
    
    $('#footer-newsletter-submit').click(function(){
        email = $('#footer-newsletter-email').val();
//        alert($(this).parent().find('#footer-newsletter-email').val());
        if ((email.indexOf(".") > 2) && (email.indexOf("@") > 0)){
           $.ajax({
                url: "/ajaxrequest/newslettersignup",
                type: 'post',
                dataType: "json",
                async: false,
                data: "email=" + email,
                success: function(data){
                    if (typeof data.error !== "undefined" && data.error) {
                        alert(data.error);
                    }else{
                        $('#footer-newsletter-form').remove();
                        $('#footer-newsletter-result').html(data.msg);
                    }
                },
                error: function (){
                    alert(t('newsletter.newsletter_signup_error'));
                    return false;
                }
            });
        }else{
            alert(t('newsletter.email_field'));
        }
        return false;
    });

    if(jQuery("#socialicons_wrap")[0]) {
        switch(jQuery('html')[0].lang.substr(0,2)) {
            case 'en':
                jQuery("#socialicons_facebook").click(function(){
                    window.open("http://www.facebook.com/FloraQueen", "facebook");
                });
                jQuery("#socialicons_twitter").click(function(){
                    window.open("http://twitter.com/FloraQueen_com", "twitter");
                });
                jQuery("#socialicons_blogger").click(function(){
                    window.open("http://www.floraqueen.com/blog/", "blog");
                });
                break;
            case 'es':
                jQuery("#socialicons_facebook").click(function(){
                   window.open("http://www.facebook.com/FloraQueen.ES", "facebook");
                });
                jQuery("#socialicons_twitter").click(function(){
                    window.open("http://twitter.com/FloraQueen_es", "twitter");
                });
                jQuery("#socialicons_blogger").click(function(){
                    window.open("http://flores.floraqueen.com/blog/", "blog");
                });
                break;
            case 'fr':
                jQuery("#socialicons_facebook").click(function(){
                    window.open("http://www.facebook.com/FloraQueen.FR", "facebook");
                });
                jQuery("#socialicons_twitter").click(function(){
                    window.open("http://twitter.com/FloraQueen_fr", "twitter");
                });
                jQuery("#socialicons_blogger").click(function(){
                    window.open("http://fleurs.floraqueen.com/blog/", "blog");
                });
                break;
            case 'de':
                jQuery("#socialicons_facebook").click(function(){
                    window.open("http://www.facebook.com/FloraQueen.DE", "facebook");
                });
                jQuery("#socialicons_twitter").click(function(){
                    window.open("http://twitter.com/FloraQueen_de", "twitter");
                });
                jQuery("#socialicons_blogger").click(function(){
                    window.open("http://blumen.floraqueen.com/blog/", "blog");
                });
                break;
            case 'it':
                jQuery("#socialicons_facebook").click(function(){
                    window.open("http://www.facebook.com/FloraQueen.IT", "facebook");
                });
                jQuery("#socialicons_twitter").click(function(){
                    window.open("http://twitter.com/FloraQueen_it", "twitter");
                });
                jQuery("#socialicons_blogger").click(function(){
                    window.open("http://www.floraqueen.it/blog/", "blog");
                });
                break;
            case 'pl':
                jQuery("#socialicons_facebook").click(function(){
                    window.open("http://www.facebook.com/FloraQueen.PL", "facebook");
                });
                jQuery("#socialicons_twitter").click(function(){
                    window.open("http://twitter.com/FloraQueen_pl", "twitter");
                });
                jQuery("#socialicons_blogger").click(function(){
                    window.open("http://www.floraqueen.pl/blog/", "blog");
                });
                break;
            default:
                jQuery("#socialicons_wrap").hide();
        }
        
        $("#footer-logos-visa").click(function(){
            window.open('https://www.paypal.com/es/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=500, height=380');
        });
        $("#footer-logos-wcafi").click(function(){
            window.open("http://www.wcafi.org/en/Clean-the-air/Clean-Air-Partners/Partners-List.aspx",'Wcafi','location=yes,status=yes,resizable=yes,scrollbars=yes,width=900,height=500');
        });
        $("#footer-logos-plant").click(function(){
            window.open("http://www.unep.org/Billiontreecampaign/CampaignNews/flora.asp",'plant','location=yes,status=yes,resizable=yes,scrollbars=yes,width=800,height=500');
        });
        $("#footer-logos-godaddy").click(function(){
            window.open("https://seal.godaddy.com:443/verifySeal?sealID=QLwOa9azhdIko8usc6pnNMu1RxyOObea61K3YOYqbSJLNNQOzRykGCVvOz",'SealVerfication','location=yes,status=yes,resizable=yes,scrollbars=no,width=560,height=415');
        });

    }
    
    if ($('#scn').length > 0) $('.select-box').css ('padding-top',($('.pedido-str').height() - $('.select-box').height())/2+'px');		// eugeni.s -> resolvemos Bug #2856
    
    /*if ($('.countries_flags').length > 0) {		// eugeni.s -> resolvemos Bug #2897
    	var colLength = Math.ceil ($('.flaglist').length / 4);
    	var countries = $('.flaglist').sort (function(a, b) {		// ordenamos países
			var compA = $(a).find('a').html().toUpperCase().replace('Ä','A').replace('Ö','O');
			var compB = $(b).find('a').html().toUpperCase().replace('Ä','A').replace('Ö','O');
			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		});
    	$('.marginleft40').append ('<div class="countries_col"></div><div class="countries_col"></div><div class="countries_col"></div><div class="countries_col"></div>');
    	var i = 0;
    	$('.countries_col').each (function () {
    		for (var a=0;a < colLength;a++) {
    			if (countries[i]) $(this).append (countries[i]);
    			i++;
    		}
    	})
    }*/

  $('a[href*=#]').click(function() { 	// eugeni.s -> scroll animado
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname) {
      var $target = $(this.hash);
      if ($(this).attr ('rel') == 'prev') $target = $target.prev();
      $target = $target.length && $target
      || $('[name=' + this.hash.slice(1) +']');
      if ($target.length) {
        var targetOffset = $target.offset().top - 15;
        $('html,body')
        .animate({scrollTop: targetOffset}, 500);
       return false;
      }
    }
  });
        

    /* botón clicable - eugeni.s 3/9/2011 */
    $('.continue-button input[type="submit"]').each (function () {
    	$(this).parents('.continue-button').click (function (e) {
    		$(this).find('input[type="submit"]')[0].click();
    		e.stopPropagation ();
    	})
    });
    $('.continue-button input[type="submit"]').click (function (e) {
    	e.stopPropagation ();
    })
    
    /* selector de tamaño clicable - eugeni.s 3/9/2011 */
    $('.product .sizes-items li').click (function (e) {
    	$(this).find('input')[0].click ();
    })
    
    /* selector de pago clicable - eugeni.s 4/9/2011 */
    $('.purchase .payment-box > ul > li').click (function () {
    	$(this).find('input')[0].click();
    })
    
    /* centrar botón compra - eugeni.s 3/9/2011 */
    $('.approve-order').css ('margin-left',($('.approve-order').parent().width() - $('.approve-order span').outerWidth())/2 +'px');
});

function t(key){ 
    /* Usage: t('card.product.guarantee'); */
    if (typeof translations[key] == "undefined"){
        var data = $.ajax({
          url: '/jstranslations?section='+key,
          dataType: 'json',
          async: false
        }).responseText;
        var Rdata = eval('(' + data+ ')');
        translations = jsonConcat(Rdata, translations);
    }
    return translations[key];
}

function redirect (url){
   $(location).attr('href', url);
}

function jsonConcat(o1, o2) {for (var key in o2) {o1[key] = o2[key];}return o1;}

