addDOMLoadEvent=(function(){var e=[],t,s,n,i,o,d=document,w=window,r='readyState',c='onreadystatechange',x=function(){n=1;clearInterval(t);while(i=e.shift())i();if(s)s[c]=''};return function(f){if(n)return f();if(!e[0]){d.addEventListener&&d.addEventListener("DOMContentLoaded",x,false);/*@cc_on@*//*@if(@_win32||@_win64)d.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");s=d.getElementById("__ie_onload");s[c]=function(){s[r]=="complete"&&x()};/*@end@*/if(/WebKit/i.test(navigator.userAgent))t=setInterval(function(){/loaded|complete/.test(d[r])&&x()},10);o=w.onload;w.onload=function(){x();o&&o()}}e.push(f)}})();

// Top menu dropdown 
function mainmenu(place){
	
	$(place+" > ul li:has(ul)").hover(function(){
		$(this).find('ul').css({visibility: "visible",display: "none"}).animate({height:'toggle'});
		},function(){
			$(this).find('ul').css({visibility: "hidden"});
		});
}

function toggleSteps() {
	$('#filterBox h3').click(function() {
		$('#couponInfoSteps').toggle(500, function() {  });
		$('#filterBox h3 a').toggleClass('open', 500);
	});
}

function defaultText() {	
	var sField = $('.global-searchinput');	
	
	sField.focusin(function() {		
		if(!this._defaultText) this._defaultText = this.value;
		if(this._defaultText == this.value) this.value = "";
	});	
	sField.focusout (function() {		
		if(this._defaultText && this.value == "")  this.value = this._defaultText;
	});	
}

//addDOMLoadEvent(defaultText);

function helpSystem() {

	var u = document.getElementById("helpContent");
	if(!u) return;
	
	u = window.location.hash;

	var listado = document.getElementById('menuHelp');
	var enlaces = listado.getElementsByTagName('a');
	var longitud = enlaces.length;
	var a,i = 0;
	var ultimo = null;		
	while (i<longitud) {
		a = enlaces[i];
		i++;
		if(!a.hash.length) continue;
		
		a.onclick = function () {
			var ind = 0;
			while (ind<longitud) {
				enlaces[ind].className = '';
				ind++;						
				};
			this.className = 'helpselected';
			if (ultimo!=null) {
				$("div#"+ultimo).fadeOut("fast");
			}else {
				document.getElementById ('help00_sec').style.display = 'none';
				};
			$("div#"+this.id+'_sec').fadeIn("slow");
			ultimo = this.id + '_sec';
			};
			
			if(u === a.hash) a.onclick();
		
		};
		
		
	if (ultimo == null) {
		document.getElementById('help00_sec').style.display = 'block';
		};
}
addDOMLoadEvent(helpSystem);

(function($,sr){ 
  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;
 
      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null; 
          };
 
          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);
 
          timeout = setTimeout(delayed, threshold || 100); 
      };
  }
	// smartresize 
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
 
})(jQuery,'smartresize');

function runSlider()
{
	 /**
         * This is the callback function which receives notification
         * right after initialisation of the carousel
         */
        function mycarousel_initCallback(carousel, state) {
            jQuery('.jcarousel-control a').bind('click', function() {
                carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
                return false;
            });

            // Pause autoscrolling if the user moves with the cursor over the clip.
            carousel.clip.hover(function() {
                carousel.stopAuto();
            }, function() {
                carousel.startAuto();
            });			
			
        };
         
        function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
            //display('Item #' + idx + ' is now the first item');
            $(".jcarousel-control a").css("background-position","left top");
            $(".jcarousel-control a#b" + idx).css("background-position","right top");
			
			if(jQuery.browser.msie && $.browser.version == "6.0")
			{
				var slider = document.getElementById("mycarousel");
				
				var ul = slider.getElementsByTagName("UL")[0];
				var ancho = slider.offsetWidth;
				
				//alert(ancho +"\n"+ ul.offsetWidth);
				
			}
			
        };
		

        // Ride the carousel...
        jQuery(document).ready(function() {            
            jQuery("#mycarousel").jcarousel({
                scroll: 1,
                auto: 10,
                wrap: 'last',
				visible: 1,
                initCallback:   mycarousel_initCallback,
                itemFirstInCallback:  mycarousel_itemFirstInCallback
            });            			
        });
		
	
			
}
//addDOMLoadEvent(runSlider);


// ====================================================
// script: Gerard Ferrandez - Ge-1-doot - DECEMBER 2K4
// http://www.dhteumeuleu.com/
// crossbrowser: IE6 - Firefox - Opera - NS7
// ====================================================
//document.onselectstart = new Function("return false")
var O   = [];
var P   = [];
var SH  = 0
var SW  = 0
var SX  = 0
var L   = 0
var H   = 0
var HS  = 0
var pS  = 5
var pS2 = pS / 2
var SPA
var xm
var ym
var mo = 0

function PObj(x){
	HS += 4 * Math.random() - 2
	if(HS < 0)HS = 0
	this.cH = Math.round(SH - pS - HS)
	o = document.createElement("span")
	SPA.appendChild(o)
	
	o = o.style;
	o.top  = this.cH + "px";
	o.left = pS * x + "px";
	o.width = pS + "px";
	o.height = 10000 + "px";
	this.pH = o;
}

function CObj(N){
	this.N = N
	o = document.createElement("span")
	SPA.appendChild(o)
	
	o = o.style;
	o.left = -100 + "px";
	o.width = pS + "px"
	o.height = pS + "px";
	o.fontSize = "1px"
	
	this.pO = o;
	this.pX = Math.round((Math.random() * SW) / pS)
	this.pY = 0
	this.zX = Math.random() - .5
	this.zY = -2

	this.run = function () {
		with (this) {
			x = Math.round(pX)
			if (pY > P[x].cH - pS) {
				if(x > 0 && P[x-1].cH > pY + pS){
					pX--
				} else if(x < SX && P[x+1].cH > pY + pS){
					pX++
				} else {
					if(pY < P[x].cH+pS) {
						P[x].cH -= pS / 2
						if(x>0) {
							if(P[x-1].cH > P[x].cH) {
								P[x-1].cH -= pS / 4
								P[x-1].pH.top = P[x-1].cH + "px";
							} else P[x].cH -= pS / 4
						}
						if(x<SX) {
							if(P[x+1].cH > P[x].cH) {
								P[x+1].cH -= pS / 4
								P[x+1].pH.top = P[x+1].cH + "px";
							} else P[x].cH -= pS / 4
						}
						P[x].pH.top = P[x].cH + "px";
					}
					
					pY = Math.random()>.9;
					pX = pY ? Math.floor((Math.random() * SW) / pS) : Math.round(xm/pS) - .5;
					pY = pY ? -pS : ym - pS2;
					
					if(pY>P[x].cH)pY = -pS
					zY = -10
					zX = Math.random()-.5
				}
			} else {
				pY += zY
				if(zY < 1)zY += .05 * (90 - N)
				pX += zX
				zX *= .99
				if(pX < 0)pX = 0; else if(pX > SX)pX = SX ;

			}

			pO.left = pX * pS - pS2 + "px";
			pO.top  = pY + "px";
			setTimeout("O["+N+"].run()", 26);
		}
	}
}

function coupons () {

$('.coupon .whiteInfo .offer_link').click(function() {
	
		$(this).parent().parent().parent().parent().attr("id","funciona");
		
		var selectedCoupon = $(this).parent().parent().parent().parent().attr('class');
		$('#funciona .whiteInfo .codigo h3').fadeIn('slow', function(){
		});	
	});
	
}

addDOMLoadEvent(coupons);

function checkContactForm () {
	
	var checkBut = document.getElementById("ssave");

	if(!checkBut) return;
	
	$(".contactPos").submit(function () {
	
		function mailchk (e){return /^([a-zA-Z0-9_\.\-\ ])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{1,4})+/.test(e);}
	
		var mailTest = document.getElementById("chk_email").value;
		
		if (mailchk(mailTest) == false) 
		{return false;}
		
		if (document.getElementById('chk_name').value == '')
		{return false;}
		
		if (document.getElementById('accept').checked == false)
		{
			$('.accept').css({'color': '#C00'})
			return false;		
		}
		
		return true;
	});
	
	
	var buttonContact = document.getElementById("ssave");
	
	buttonContact.onmouseover = function () {
		this.style.backgroundPosition = 'left bottom';
	}
	
	buttonContact.onmouseout = function () {
		this.style.backgroundPosition = 'left top';
	}
	
	/*buttonContact.onclick = function() {
		alert (return checkContactForm();)
	}*/
	
	
}

addDOMLoadEvent(checkContactForm);

function resaltados() {

	//common form
	
	var butForm = document.getElementById("ssubmit");
	
	if (!butForm) return;	
	
	butForm.onmouseover = function () {
		this.style.backgroundPosition = 'left bottom';
	}
	
	butForm.onmouseout = function () {
		this.style.backgroundPosition = 'left top';
	}
	
	//modulo home busqueda
	
	var checkmodule = document.getElementById("searchoffershome");	
	if (!checkmodule)
	return false;	
	var buttonModule = document.getElementById('ssearchhome');	
	var selectedInput = document.getElementById('soffershome').getElementsByTagName("INPUT")[1];	
	selectedInput._defaultText = selectedInput.value;	
	selectedInput.onfocus = function() {
		if(!this._defaultText) this._defaultText = this.value;		
		if(this._defaultText == this.value) this.value = "";
	}	
	selectedInput.onblur = function() {
		if(this._defaultText && this.value == "")  this.value = this._defaultText;
	}	
	buttonModule.onclick = function () {		
		if(!this._defaultText) this._defaultText = this.value;
		if(selectedInput._defaultText == selectedInput.value) selectedInput.value = "";		
	}	
	buttonModule.onmouseover = function () {
		this.style.backgroundPosition = 'left bottom';
	}	
	buttonModule.onmouseout = function () {
		this.style.backgroundPosition = 'left top';
	}	
	var categoriesSelect = document.getElementById('allcategories');	
	categoriesSelect.onchange = function() {		
		if (selectedInput._defaultText == selectedInput.value) {
		selectedInput.value = "";
		}
	}	
}

addDOMLoadEvent(resaltados);

function alignCoupons3 () {

	var checkPage = document.getElementById("allCoupons");
	if(!checkPage)
	return false;
	
	var todosCupones = document.getElementsByClassName('coupons', checkPage, 'div');
	var totalCupones = todosCupones.length;
	var ind = 0;
	while (ind<totalCupones) {		
			
		if ((ind + 1) % 3 == 0) {
			todosCupones[ind].style.marginRight='0px';
		}else {
			todosCupones[ind].style.marginRight='37px';
		}
		
		todosCupones[ind].style.marginBottom='37px';
		ind++;
	}
}
addDOMLoadEvent(alignCoupons3);

function alignCoupons2 () {

	var checkPage = document.getElementById("homemodulecoupons");
	if(!checkPage)
	return false;
	
	var todosCupones = document.getElementsByClassName('coupons', checkPage, 'div');
	var totalCupones = todosCupones.length;
	var ind = 0;
	while (ind<totalCupones) {		
			
		if ((ind + 1) % 2 == 0) {
			todosCupones[ind].style.marginRight='0px';
		}else {
			todosCupones[ind].style.marginRight='43px';
		}
		
		todosCupones[ind].style.marginBottom='43px';
		ind++;
	}
}
addDOMLoadEvent(alignCoupons2);

if (!document.getElementsByClassName) {
	document.getElementsByClassName = function(searchClass, node, tag)
	{
		node = node || document;
		tag = tag || '*';
		
		var els = node.getElementsByTagName(tag), i = els.length, j = 0, e = [];
		while(i--)
			if(els[i].className.indexOf(searchClass) != -1)
				e[j++] = els[i];
		
		return e.reverse();
	}
}

/**
 * Search posicionamiento
 */

	function setSearchPosition() {
		var zoomer = document.getElementById('global-chooseSearchType');
		if(!zoomer) return;			
		$('#global-searchChoices').css("display",("none")); 	
		var xSearch = $('#global-searchform').offset().left;
		var ySearch = $('#global-searchform').offset().top;		
		$("#global-searchChoices").css( { "left":xSearch + "px", "top":(ySearch + 10) + "px" } );
		$('#global-searchChoices').css("display",("block"));  
	}
	//addDOMLoadEvent(setSearchPosition);
 
/**
 * setSearch
 */

	function setSearchType() {
		var zoomer = document.getElementById('global-chooseSearchType');
		if(!zoomer) return;			
		var searchOptions = document.getElementById('global-subnav-list-search');
		var searchOpen = false;		
		document.onclick = function(evt) {			
			evt = evt || event;
			var elemento = evt.target || evt.srcElement;
			if (elemento.id == 'global-chooseSearchType') {
				searchOptions.style.display = 'block';
			}else{
				searchOptions.style.display = 'none';
			}	
		} 
		var searchList = document.getElementById('global-subnav-list-search');
		var searchListOptions = searchList.getElementsByTagName('li');
		var searchListLong = searchListOptions.length;
		var ind = 0;		
		var searchInput = $('#global-searchinput');		
		alert(1);
		var action = '';
		while (ind<searchListLong) { 	
			if(searchListOptions[ind].id != ''){
				action = searchListOptions[ind].id.split('-');
				action = action[3];
				action = (action == 'all') ? '' : action ;				
				switch(action){				
					case 'offers':
						searchListOptions[ind].onclick = function() { 
							$(searchListOptions[2]).removeClass('searchOptionSelected');
							$(searchListOptions[3]).removeClass('searchOptionSelected');
							$(searchListOptions[4]).removeClass('searchOptionSelected');
							$(this).addClass('searchOptionSelected');
							var indice = 0;
							while (indice<searchListLong){
								if (searchInput.value == searchListOptions[indice].innerHTML || searchInput.value == searchInput._defaultText) {
									searchInput.value = this.innerHTML;
									searchInput._defaultText = this.innerHTML;
								}
								indice++;
							}							
							changeAction( 'offers' );
						};
						break;
					case 'products':
						searchListOptions[ind].onclick = function() { 
							$(searchListOptions[1]).removeClass('searchOptionSelected');
							$(searchListOptions[3]).removeClass('searchOptionSelected');
							$(searchListOptions[4]).removeClass('searchOptionSelected');
							$(this).addClass('searchOptionSelected');
							var indice = 0;
							while (indice<searchListLong){
								if (searchInput.value == searchListOptions[indice].innerHTML || searchInput.value == searchInput._defaultText) {
									searchInput.value = this.innerHTML;
									searchInput._defaultText = this.innerHTML;
								}
								indice++;
							}	
							changeAction( 'products' )
						};
						break;
					case 'coupons':
						searchListOptions[ind].onclick = function() { 
							$(searchListOptions[1]).removeClass('searchOptionSelected');
							$(searchListOptions[2]).removeClass('searchOptionSelected');
							$(searchListOptions[4]).removeClass('searchOptionSelected');
							$(this).addClass('searchOptionSelected');
							var indice = 0;
							while (indice<searchListLong){
								if (searchInput.value == searchListOptions[indice].innerHTML || searchInput.value == searchInput._defaultText) {
									searchInput.value = this.innerHTML;
									searchInput._defaultText = this.innerHTML;
								}
								indice++;
							}	
							changeAction( 'coupons' )
						};
						break;
					default:
						searchListOptions[ind].onclick = function()
						{ 
							$(searchListOptions[1]).removeClass('searchOptionSelected');
							$(searchListOptions[2]).removeClass('searchOptionSelected');
							$(searchListOptions[3]).removeClass('searchOptionSelected');
							$(this).addClass('searchOptionSelected');
							var indice = 0;
							while (indice<searchListLong){
								if (searchInput.value == searchListOptions[indice].innerHTML || searchInput.value == searchInput._defaultText) {
									searchInput.value = this.innerHTML;
									searchInput._defaultText = this.innerHTML;
								}
								indice++;
							}	
							changeAction( '' )
						};
				}				
			}
			ind++;
		}		
		var searchButton = document.getElementById('global-searchsubmit');
		searchInput._defaultText = searchInput.value;
		searchInput.onfocus = function() {
			if(!this._defaultText) this._defaultText = this.value;
			if(this._defaultText == this.value) this.value = "";
		}
		
		searchInput.onblur = function()
		{
			if(this._defaultText && this.value == "")  this.value = this._defaultText;
		}
		
		searchButton.onclick = function () {
						
			if(!this._defaultText) this._defaultText = this.value;
			if(searchInput._defaultText == searchInput.value) searchInput.value = "";
			
		}
		
	}
	addDOMLoadEvent(setSearchType);
/**
 * CheckForm
 */
 
 // -----------------------------------------------------------------------
// form check
var frmchk =
{
	id			: 'shareForm',
	fields		:
	{
		// ID, checking type, related value
		'share_name':["lenght",6],
		'share_email':["email"],
		'share_friend_mail':["email"]
		//'con5':["lenght",10]
	},
	
	// -----------------------------------------------------------
	main		: function()
	{
		var frm = frmchk.$(frmchk.id);
		
		if(!frm) return;
		frm.onsubmit = frmchk.onsubmit;
		
		var a,n,b;
		
		for(n in frmchk.fields)
		{
			a = frmchk.$(n);
			b = frmchk.fields[n];
			a.onkeyup = frmchk.key;
			a._tipus = b[0];
			a._relvalor = b[1];
			a._correcte = false;
			
			a.onkeyup(); /* per camps amb valors posats per la memoria del navegador */
		}
		/*
		a = document.getElementById("fmr_hover");
		if(!a) return;
		a.onmouseover = function(){this.style.backgroundPosition = "left bottom";}
		a.onmouseout = function(){this.style.backgroundPosition = "left top";}
		*/
	
	},
	
	// -----------------------------------------------------------
	onsubmit	: function()
	{
		var n, k = 0, c = 0, o;
		
		for(n in frmchk.fields)
		{
			o = frmchk.$(n);
			o.value = frmchk.trim(o.value);
			o.onkeyup();
			k += o._correcte;
			c++;
			
			if(!o._correcte)
			{
				frmchk.errorInfo.start(o.id);
				return false;
			}
		}
		
		return k == c ? true : false;
	},
	
	// -----------------------------------------------------------
	key			: function()
	{
		switch(this._tipus)
		{
			case	"lenght":
				frmchk.status(this.id,frmchk.trim(this.value).length >= this._relvalor);
				break;
				
			case	"email":
				frmchk.status(this.id,frmchk.mailchk(frmchk.trim(this.value)));
				frmchk.status(this._relvalor,frmchk.trim(this.value) == frmchk.trim(frmchk.$(this._relvalor).value));
				break;
				
			case	"compare":
				frmchk.status(this.id,frmchk.trim(this.value) == frmchk.trim(frmchk.$(this._relvalor).value));
				break;
		}
	},
	
	// -----------------------------------------------------------
	status		: function(id,s)
	{
		var o = frmchk.$(id);
		o._correcte = s;
		
		o.style.color = s ? "#000" : "#D00";
	},
	
	// -----------------------------------------------------------
	errorInfo	: 
	{
		start	: function(id)
		{
			frmchk._errorObj = frmchk.$(id);
			
			frmchk._errorObj._errorStatus = 0;
			frmchk.errorInfo.timer();
		},
		
		timer	: function(a)
		{
			if(frmchk._errorObj._errorStatus % 2)
				frmchk._errorObj.select();
			else
			{
				var a = frmchk._errorObj.value;
				frmchk._errorObj.value = "";
				frmchk._errorObj.value = a;
			}
			
			if(frmchk._errorObj._errorStatus++ < 11)
				setTimeout(frmchk.errorInfo.timer,80);
			else
				frmchk._errorObj.select();
		}
		
	},
	
	$			: function(e){return document.getElementById(e);},
	trim		: function(s){return s.replace(/^\s*|\s*$/g,"");},
	mailchk		: function(s){return /^([a-zA-Z0-9_\.\-\ ])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{1,4})+/.test(s);}

};
//addDOMLoadEvent(frmchk.main);
 
/**
 * scaleImage 0.1
 * 
 * Rendez vos sites glissant !
 *
 * Copyright (c) 2008 Benoit G (http://www.tim-burton.net) based upon
 * Licensed under the Creative Commons License:
 * http://creativecommons.org/licenses/by/3.0/
 *
 * Date: 2008-08-25
 */
 
	(function($){
		$.fn.scaleImage = function(options) {		
			var defaults = {
			maxwidth: 118,
			linkclass:'productsZoomer',
			icon:true
			//thickbox:true
			};
			var options = $.extend(defaults, options);	
			return this.each(function() {
				obj = $(this);
				
				var width = obj.width();
				var height = obj.height();
				if (width > options.maxwidth) {
					//Set variables	for manipulation
					var ratio = (height / width );
					var new_width = options.maxwidth;
					var new_height = (new_width * ratio);
					var classes = options.linkclass+' scaleImage';

					//thickbox
					if (options.thickbox == true) {
						var img_full_link = obj.attr('src');
						obj.wrap('<a class="thickbox" title="'+obj.attr('alt')+'" href="'+img_full_link+'"></a>');
						//tb_init(obj.parent('a'));
					}
					
					//Shrink the image and add link to full-sized image
					obj.height(new_height).width(new_width);
					obj.addClass(classes);
					
					//zoom icon
					if (options.icon == true) {
						obj.after('<div class="thumb-zoom"> </div>');
						obj.hover(function(){
							$(this).next('.thumb-zoom').addClass("hover");
						},function(){
							$(this).next('.thumb-zoom').removeClass("hover");
						});
					}
				
				}
				
			});			
		};
	})(jQuery);	
	
	function resetEmailFormContact(lang){
		contactInfoTxtArea = '';
		$('#chk_name').val('');
		$('#chk_name_sta').css({'display' : 'none'});		
		$('#chk_email').val('');
		$('#chk_email_sta').css({'display' : 'none'});
		$('#contactReason').val('0');
		switch(lang){
			case 'br':
				contactInfoTxtArea = "Escreva aqui sua mensagem. Se você tiver alguma dúvida sobre uma oferta, cupom ou outros produtos concretos, por favor, especifique.";
				break;
			case 'en':
				contactInfoTxtArea = "Write your message here. If you have a question about a particular offer, coupon or product, please let us know the link location.";
				break;
			case 'es':
				contactInfoTxtArea = "Escribe aquí tu mensaje. Si tienes cualquier duda sobre una oferta, cupón o producto concretos, especifícanos cuál.";
				break;
			case 'fr':
				contactInfoTxtArea = "Veuillez écrire votre message ici. Si vous avez une question au sujet d’une offre, d’un coupon ou d’un produit en particulier, veuillez nous indiquer ses références.";
				break;
			case 'it':
				contactInfoTxtArea = "Scrivi il tuo messagio qui. Se vuoi fare una domanda su un'offerta, un coupon o un prodotto in particolare, per favore specifica qual'è.";
				break;				
		}
		$('#contactInfoTxtArea').val(contactInfoTxtArea);		
		$('#contactInfoTxtArea_sta').css({'display' : 'none'})
		$('#accept').attr('checked', false);
	}
	
	function showEmailFormContact(){
						
	    $("#float_email_contact").fadeIn('slow');
	    $('#global-chooseSearchType').hide();
	    var lang = 'en';
	    if($('#content_english').hasClass('hover')) {
	    	lang = 'en';
	    } else if($('#content_spain').hasClass('hover')) {
	    	lang = 'es';    	
	    } else if($('#content_france').hasClass('hover')) {
	    	lang = 'fr';    	
	    } else if($('#content_italy').hasClass('hover')) {
	    	lang = 'it';  
	    } else if($('#content_brazil').hasClass('hover')) {
	    	lang = 'pt';  
	    } /*else if($('#content_brazil').hasClass('hover')) {
	    	lang = 'de';  
	    }*/
		
		if (lang == 'pt')
	    	$("#contactInfo").attr("action", "/br/contact/brsubmitted");
	    else if (lang == 'en')
	    	$("#contactInfo").attr("action", "/en/contact/brsubmitted");
	    else
	    	$("#contactInfo").attr("action", "/"+lang+"/contact/submitted");
		
		resetEmailFormContact(lang);		
		
	    $('#label_contact_name').html(labelContactName[lang]);
	    $('#label_contact_email').html(labelContactMail[lang]);
	    $('#label_contact_subject').html(labelContactSubject[lang]);
	    $('#label_contact_msg').html(labelContactMsg[lang]);
	    $('#contactInfoTxtArea').html(contactInfoTxtArea[lang]);
	    $('#code_contact_note').html(codeContactNote[lang]);
	    $('#label_accept_checkbox').html(acceptCheckBox[lang]);
	    $('#ssave').val(ssave[lang]);
	    
		//select options
	    $('#contactReason option').each(function(i){
	    	j = lang + (i+1);
	    	$(this).val(selectOpt[j]);
	    	$(this).text(selectOpt[j]);
	    })
	    /*
	    data = "item="+item ;
	    
	      $.ajax({
	          url: url,
	          cache: false,
	          data : data,
	          success: function(html){
	 
	            window.scrollTo(0,0);
	 
	            $("#float_content_contact").html(html);
	            $("#float_content_contact").show();
	 
	            //$('#waitDiv').fadeOut('slow');
	 
	          }
	        });
	      */
    }
	
	
    function showEmailForm(item, url){

    	
   $("#float_email").fadeIn('slow');
    $('#global-chooseSearchType').hide();
      data = "item="+item ;
 
      $.ajax({
          url: url,
          cache: false,
          data : data,
          success: function(html){
 
            window.scrollTo(0,0);
 
            $("#float_content").html(html);
            $("#float_content").show();
 
            //$('#waitDiv').fadeOut('slow');
 
          }
        });
    }

     function sendEmailForm(url){
 
      data = "email=" + $('#share_email').val();
      data = data + "&friend_mail=" + $('#share_friend_mail').val();
      data = data + "&name=" + $('#share_name').val();
      data = data + "&item=" + $('#share_item').val();
      data = data + "&message=" + $('#share_message').val();
      data = data + "&type=" + $('#share_type').val(); 
      data = data + "&banner_description=" + $('#banner_description').val();
      data = data + "&banner_title=" + $('#banner_title').val();
      data = data + "&action_button_url=" + $('#action_button_url').val();
      
      $.ajax({
          url: url,
          cache: false,
          data: data,
          type: 'POST',
          beforeSend: function(){
 
          loading = '<div class="cover">';
          loading = loading + '<div class="emailheader"><h1>E-mail</h1></div><!-- emailheader -->';
          loading = loading + '<div class="emailFormCont" style="text-align:center; vertical-align:middle;" >';
          loading = loading + '<img src="/images/loading.gif" style="float:none;" />';
          loading = loading + '</div><!-- emailFormCont -->';
          loading = loading + '<div class="emailFooter"></div><!-- emailFooter -->';
          loading = loading + '</div><!-- cover -->';
 
          $("#float_content").html(loading);
          },
          success: function(html){
 
            window.scrollTo(0,0);
 
            $("#float_content").html(html);
            $("#float_content").show();
 
            //$('#waitDiv').hide();
 
          }
        });
    }
 
    function closeEmail(){
      $('#float_email').fadeOut('slow');
	  $('#float_email_contact').fadeOut('slow');
    $('#global-chooseSearchType').fadeIn('slow');
    }
	
	
	/**
	 * Get the filtered results depending on the type and shows the filters related
	 * 
	 * @param string lang language
	 * @param string type of data (coupons, products, stores, overview)
	 * @param string tabClass active tab class
	 * @return
	 */
	function getFilteredResults( lang, type, tabClass, query ){
		
		if(tabClass!= undefined && tabClass != ''){
			$('#subnav_home a').attr('id', '');
			$('.'+tabClass).attr('id', 'subnavActivo');
		}
		
		if(query == undefined ) query = '';
		
		$.ajax({
	        url: '/'+lang+'/ajax/show-filters/ftype/' + type + '/' + query,
	        cache: true,
	        beforeSend: function(){
	            
	            $("#filterBox").html('<img src="/images/loading.gif" style="float:none;" />');
	        },
	        success: function(html){
	            
	            $("#filterBox").html(html);
	        }
	    });
	    
		$.ajax({
	        url: '/'+lang+'/ajax/get-filtered-' + type + '/' + query,
	        cache: true,
	        beforeSend: function(){
	            
	            $("#mainResults").html('<img src="/images/loading.gif" style="float:none;" />');
	        },
	        success: function(html){
	            
	            $("#mainResults").html(html);
	        }
	    });
		
	}
	
/* FILTER  */
function RemoveCheck(id) {
	$('#li'+id).remove();
	$( '#check'+id ).attr( 'checked', $( '#check'+id ).is( ':checked' ) ? '' : 'checked' );
}

function checkIt(id) {
	var el=$('#check'+id).attr('checked');	
	if(!el)	{	
		$('#li'+id).remove();		
	} else {
		$("#sortable").append('<li id="li'+id+'"><div class="smallTab"><a href="#" class="linkSubcat">'+(id+1)+' opcion</a><a href="#" onclick="RemoveCheck('+id+'); return false;" ><img title="[cat_81_title]" alt="[cat_81_alt]" src="/images/moreYellow.png"></a></div></li>');
		$("#sortable").sortable( 'refresh' )
	}	
	$('#title'+id).attr('disabled',!el);
	$('#user'+id).attr('disabled',!el);
}

addDOMLoadEvent(checkIt);

function serial() {
	var newArr = new Array();
	if(document.getElementById("sortable"))	{
		var s = $("#sortable").sortable('toArray');		
		for(var i=0;i<s.length;i++) {
			s[i]=s[i].replace('li','');
			newArr.push({
				id:s[i],
				position:newArr.length,
				title: encodeURIComponent($('#title'+s[i]).val()),
				feed:encodeURIComponent($('#user'+s[i]).val())
			});
		}
	}	
	return newArr;
}

//addDOMLoadEvent(serial);
var lastSer = "";

function getSortable(edit) {
	var dat = serial();
	if(!dat.length)	{
		showDialog('You haven\'t chosen any services for your widget!');
		return false;
	}	
	var str=new Array();
	for(var i=0;i<dat.length;i++) {
		if(!dat[i].title || !dat[i].feed || (dat[i].id==5 && (!validateURL(decodeURIComponent(dat[i].feed)) || !validateURL($('#cUF').val()) ))){
			showDialog('One of the services you\'ve chosen is not filled in properly!');
			return false;
		}		
		str[i]="sB["+i+"][id]="+dat[i].id+"&sB["+i+"][title]="+dat[i].title+"&sB["+i+"][feed]="+dat[i].feed;
		if(dat[i].id==5) {
			str[i]+="&sB["+i+"][customURL]="+encodeURIComponent($('#cUF').val());
		}
	}	
	if(document.getElementById('emailEdit') && $('#emailEdit').val().length) {
		if(validateEmail($('#emailEdit').val())){
			str[str.length]='emailEdit='+encodeURIComponent($('#emailEdit').val())+'&notifyMe='+($('#notifyMe').attr('checked')?'1':'0');
		} else {
			showDialog('The email address, you\'ve entered, is not valid');
			return false;
		}
	}	
	if(edit) str.push('editLink='+edit);	
	var tmpJoin = str.join("&");	
	if(lastSer==tmpJoin) return false;
	lastSer=tmpJoin;
	$('#getCode').hide();
	showDialog('<img src="/images/18-0.gif" style="margin:20px 0px 0px 110px" />','Generating your widget');	
	$.ajax({
		type: "POST",
		url: "/ajax/generate.aj.php",
		data: tmpJoin,
		dataType: 'json',
		success: function(msg){
			if(parseInt(msg.status)!=1){
				$('#dialog').html(msg.txt);
			}else{
				$('#dialog').dialog('destroy');
				$('#responseTxt').html(msg.txt);
				$.scrollTo('#generate',800);
			}
		}
	 });
}

function showDialog(str,strtitle) {
	if(!strtitle) strtitle='Error message';
	$('#dialog').dialog('destroy');
	$('#dialog').show();
	$('#dialog').html(str);	
	$("#dialog").dialog({
		resizable: false,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.9
		},
		title:strtitle,
		buttons: {
			'OK': function() {
				$(this).dialog( 'destroy' )
				$('#dialog').hide();
			}
		}
	});
}

function setCookie () {
	var futdate = new Date();
	var expdate = futdate.getTime();
	expdate += 1440*1000; //expires in 1 hour(milliseconds)
	futdate.setTime(expdate);
	$.cookie('adultOB', 'true',{expires:futdate, path: '/'});
}

function adultCheck() {
	var adultOB = $.cookie('adultOB');
	if(adultOB == null)
		setAdult();
	else {
		$('.miniProductShare_adultcontent').css('display','none');
		$('.miniProductShare_noadultcontent').css('display','');
		return false;
	}
}

// Adult content detection
function setAdult() {
	// Create substitute
	var blockImage		=	'<div class="blockImg"><i>'+ Adult_Majority	+'</i><strong>'+ Adult_Access +'</strong></div>';
	$(blockImage).appendTo('.adult_content .croper');

	var adultHeader		=	'<h5 class="adultHeader">'+ Adult_PopUp_Title +'</h5>';
	var adultContent	=	'<div class="adultContent clearfix"><p>'+ Adult_PopUp_Text_1 +'.</p><a href="#" onclick="$.fancybox.close(); showAdult(); return false;" class="adultAccept"><span>&nbsp;</span>'+ Adult_PopUp_Text_2 +'</a><a href="#" onclick="$.fancybox.close(); return false;" class="adultCancel">'+ Adult_Cancel +'</a></div>';

	// Hide adult content
	$('.adult_content .croper img').css('display','none');
	$('.adult_content .croper .productsZoomer').css('display','none');
	$('.adult_content').css('cursor','pointer');
	$('.miniProductShare_adultcontent').css('display','');
	$('.miniProductShare_noadultcontent').css('display','none');
	
	// Modal window
	$(document).ready(function() {
		$('.adult_content').fancybox(
			{
				autoScale		:	'true',
				titleShow		:	'show',
				titlePosition	:	'over',
				padding			:	'0',
				overlayColor	:	'#000',
				overlayOpacity	: 	'0.5',
				title			:	adultHeader,
				content			:	adultContent,
				width			:	500
			});			
	});
}

function showAdult() {
	$('.adult_content').unbind('click');
	$('.blockImg').css('display','none');
	$('.adult_content .croper img').css('display','block');
	$('.adult_content .croper .productsZoomer').css('display','block');
	$('.adult_content').css('cursor','default');
	$('.miniProductShare_adultcontent').css('display','none');
	$('.miniProductShare_noadultcontent').css('display','');
	setCookie();
}

function showCouponCode(coupon) {
	var selectedCoupon = $(coupon).parent().parent().parent().attr('id');
	$('#' + selectedCoupon + ' .showCode').slideDown('slow', function() {
		$('#' + selectedCoupon + ' .txt1').css('display','none');
		$('#' + selectedCoupon + ' .txt2').css('display','block');
	});
}

//functions to be run only in the home page
function homeActions(){
	$('#offers p.title span').each(function(index) {											   
		if($(this).height()>14){					    	
			$(this).parent().addClass('two_lines')
		}
	});	
	$.featureList(
		$("#tabs li a"),
		$("#output li.banner_container"), {
			start_item	:	1
		}
	);	
	$("#offers li").mouseenter(function() {				   
	   $(this).data('over', "true");
	   $(this).delay(400).fadeIn(0,function(){				   	
			if($(this).data('over')=="true"){
				$(this).addClass('over');
			}
	   });					   
	})		
	$("#offers li").mouseleave(function() {				 	
		$(this).removeClass('over');
		$(this).data('over', "false");
	});
		
	
	$("#twitter_carousel").jCarouselLite({btnNext:false, btnPrev:false,auto:3000,speed:1000,vertical:true,visible:3});
}

//return the factorial of the given number
function factorial(num){
	result=0;
	for (i=1;i<10;i++){
		result=result+i*counter_random_increment;
	}		
	return result;
}

function deleteCookie(name) {
    var dtExpireDel = new Date();
    dtExpireDel.setTime(dtExpireDel.getTime() - 1);
    
    document.cookie = "osid=0; expires="+dtExpireDel+"; path=/"; //setCookie
}

var sweepChecks = true;

$(document).ready(function() {

	// Homepage functions
	if (actual_page=="homepage"){
		homeActions();      
	}
	//create counter, since the numer given				
	var myCounter = new flipCounter('the_counter', {value:(counter_init_value-factorial(counter_max_iteration)), inc:counter_random_increment, pace:counter_pace, auto:true});
	// Filtering
	if (sweepChecks) {
		var i=0;
		while(document.getElementById('check'+i)){
			$('#check'+i).attr('checked',false);
			i++;
		}
	} else if (tabs.length) {
		var i=0;
		while(document.getElementById('check'+i)) {
			if(!tabs[i]) {
				$('#check'+i).attr('checked',false);
				i++;
				continue;
			}			
			$('#check'+i).attr('checked',true);			
			$('#title'+i).val(tabs[i].name);
			$('#title'+i).attr('disabled',false);			
			$('#user'+i).val(i==5?tabs[i].feed:tabs[i].uname);
			$('#user'+i).attr('disabled',false);			
			if (i==5) {
				$('#customURL').show();
				$('#cUF').val(tabs[i].customURL);
			}			
			i++;
		}
	}
	
  	$('#liDef').remove(); 
	$('#topBar .replaceLink').attr('onclick', '$.scrollTo(this.hash,800);return false;');
	
	if($('a').hasClass('productsZoomer')){		
		$("a.productsZoomer").fancybox({
			autoScale: 'true',
			titleShow: 'show',
			titlePosition: 'over',
			padding: '0',
			overlayColor : '#000',
			overlayOpacity: '0.5'
		});
	}		
	if(document.getElementById("carouselProducts"))  	{					
			/*$("#carouselProducts").carousel( { 
					pagination: true,
					dispItems: 3,
					direction: "horizontal"
			}
		);*/
			
	}
	if(document.getElementById("productsCarousel"))  	{					
			$("#productsCarousel div").jCarouselLite({
					btnNext: ".next",
					btnPrev: ".prev",
					auto:3000,
					speed:1000,
					visible:2
			});
	}
	$('.resizes').load(function() {
		// Handler for .load() called.
		$('.resizes').scaleImage();			
	});
	//$('ul#twitter_update_list').carouFredSel();
	//$("#contactReason").msDropDown();
	$("body select").msDropDown();
	defaultText();
	mainmenu("header");
	mainmenu("nav");

	
	$('.menuStores').columnize({ 
		columns		: 5
		});
		
	$('.menuCategories').columnize({ 
		columns		: 4
		});
	$('.storesList li.az ul').columnize({ 
		columns		: 3,
		 balanced		:true		 
		});
	$('.storesList ul.byCat').columnize({ 
		columns		: 3,
		 balanced		:true		 
		});
	/*$('.all_categories ul.allcatParent').columnize({ 
		columns		: 3		 
		});
	*/
	//$('.storesList li.cat ul').columnize({ columns		: 3});
	
	$('.menuCategories').css('display','none');
	$('.menuCategories').css('visibility','visible');
	$('.menuStores').css('display','none');
	$('.menuStores').css('visibility','visible');		
			
$(".nav_stores").click(function(){
		if(!$(this).hasClass("selected")){								
				var sel=($(".nav_stores.selected").attr("href"));
				var sel2=$(this).attr("href");
				$(sel).fadeOut("fast", function() {						
						$(sel2).fadeIn("fast");												
				});
				$(".nav_stores.selected").removeClass("selected");
				$(this).addClass("selected");
				
			}
	});	
	
	
});  //$(document).ready(function()

/**
 * function to get the url vars as array
 * 
 * @return string
 */
function getUrlParams()
{
	// get the current URL
	 var url = window.location.toString();
	 //get the parameters
	 url.match(/\?(.+)$/);
	 var params = RegExp.$1;
	 // split up the query string and store in an
	 // associative array
	 var params = params.split("&");
	 var queryStringList = {};
	 
	 for(var i=0;i<params.length;i++)
	 {
	     var tmp = params[i].split("=");
	     queryStringList[tmp[0]] = unescape(tmp[1]);
	 }	
	 
	 return queryStringList;
}

/**
 * function to retrieve by ajax the next coupons to show
 * 
 * @return void
 */
function ask_coupon()
{
	
	var params = '';
	var queryStringList;
	var recsPerPage = 10;
	
	queryStringList = getUrlParams();
	for(var i in queryStringList){
		if (params == '')
			params = '?';
		else 
			params += '&';
		params += i+"="+queryStringList[i];
	}

	if (jQuery('#form_scroll_vars_category_list').val() != ''){
		if (params == '')
			params = '?';
		else 
			params += '&';
		params += 'cl='+jQuery('#form_scroll_vars_category_list').val();
	}
	
	// control vars
	// total results found	
	// results shown
	// nextPage
	if (params == '')
		params = '?';
	else 
		params += '&';	
	var nextPage =  parseInt(jQuery('#form_scroll_vars_page').val(), 10) + 1;
	params += 'tr=' + jQuery('#form_scroll_vars_total_results').val() + '&rs=' + jQuery('#form_scroll_vars_results_shown').val() + '&np=' + nextPage;
	
	if (jQuery('#form_scroll_vars_advertiser_id').val() != '')
		params += '&a='+jQuery('#form_scroll_vars_advertiser_id').val();
	
	if (parseInt(jQuery('#form_scroll_vars_results_shown').val()) < parseInt(jQuery('#form_scroll_vars_total_results').val())){	
		jQuery.ajax({
	        url: '/'+language+'/ajax/getlistofcoupons'+params,
	        type: 'get',
	        beforeSend: function(){
				//increase var page
	        },
	        success: function(html){				
				$(".coupons:last").after('<a class="back_top" href="#wrapper">'+back_top+'</a>'+html);				
				$('div#last_msg_loader').empty();
				couponAsked=0;
				//increase the total results shown
				jQuery('#form_scroll_vars_results_shown').val(parseInt(jQuery('#form_scroll_vars_results_shown').val()) + recsPerPage);
				jQuery('#form_scroll_vars_page').val(nextPage);
	        },
	        dataType: 'html'
	    });
	}else{
		$('div#last_msg_loader').empty();
	}
	
}

function header_click(searchElementId, searchFormId){	
 	//load obSuggestEntries	
	var entries = '';
	var autocompleteCategories = new Array();	
	var typeOfDataToShow = '';
	
	switch(searchElementId){
		case 'stores-searchinput':
			// show only stores
			typeOfDataToShow = 'stores';
			break;
		case 'categories-searchinput': 
			// show only categories
			typeOfDataToShow = 'categories';
			break;
		default: 
			// show stores and categories	
			typeOfDataToShow = '';
	}
	$.get("/"+language+"/ajax/getObSuggestEntries?typeOfDataToShow="+typeOfDataToShow, 
			{},
			function(data){
				entries = data; //alert("Load ob entries");				
			 }, 
			 "json");
	
		
	//Search autocomplete
	$.widget("custom.catcomplete", $.ui.autocomplete, {		
		_renderMenu: function(ul,items) {
			var self = this,						
			currentCategory = "";	
			var cont = 0;						
			$.each(items, function( index, item ) {
				if(index < 10){			
					if (item.category != currentCategory ) {
						if(index>0){
							var hasBorder="hasBorder";
						}else{
							var hasBorder=""
						}
						$( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a class='newCat "+hasBorder+" '>" + item.label + "<span>"+ item.category + "</span></a>" )
						.appendTo( ul );
						currentCategory = item.category;
						autocompleteCategories[cont] = item.category;
						cont = cont + 1;						
					} else {
						self._renderItem( ul, item );
					}								
				};	
			});
		}
	});
	
	var accentMap = {
			'á':'a', 'à':'a', 'â':'a', 'ã':'a', 'ä':'a', 'å':'a',						
			'é':'e', 'è':'e', 'ê':'e', 'ë':'e',
			'í':'i', 'ì':'i', 'î':'i', 'ï':'i', 
			'ó':'o', 'ò':'o', 'ô':'o', 'õ':'o', 'ö':'o',						
			'ú':'u', 'ù':'u', 'û':'u', 'ü':'u', 
			'ý':'y', 'ÿ':'y'							
	};
	
	var normalize = function( term ) {
		var ret = "";
		for ( var i = 0; i < term.length; i++ ) {
			ret += accentMap[ term.charAt(i) ] || term.charAt(i);
		}
		return ret;
	};
	
	//$("#global-searchinput").catcomplete({
	$('#' + searchElementId).catcomplete({		
		minLength	: 3,

		source		: function( request, response ) {
						//folding accents
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
						
						response( $.grep( entries, function( value ) {
								value = value.label || value.value || value;
								return matcher.test( value ) || matcher.test( normalize( value ) );
							}) );
					},
		
		close		: function(event,ui) {
						//alert($(this).attr('value'));
						var miBusqueda = ($(this).attr('value'));	
						var miBusquedaId = ($(this).attr('type'));	
						if(miBusqueda.length > 3) {
							$('.ui-menu li').each(function(index){		
								var selectBusqueda = $(this).text();
								var spantxt = $(this).children("a:first-child").children("span:first-child").text();
								if(spantxt.length) {
									selectBusqueda = selectBusqueda.substr(0, selectBusqueda.length-spantxt.length);
								}
								if (selectBusqueda == miBusqueda) {
									$(entries).each(function(entrieId){
										if(entries[entrieId].value == miBusqueda){
											selEntrieId = entrieId;
											return false;
											//selEntrieId = entrieId;
										}
									});
									params = '';
									/*if (searchElementId == 'stores-searchinput' || searchElementId == 'categories-searchinput'){
										alert(location.host);
										alert(location.pathname);
										alert(location.search);
										//actionUrl = "/" + language + "/coupons/home/" + params;
										params = '?qs='+$('#stores-searchinput').val()+'&qc='+$('#categories-searchinput').val()+'&pt=' + $('#pt').val();
										actionUrl = 'http://'+location.host + location.pathname + '/' + params 
									}else */
									if(searchElementId == 'global-searchinput'){
										actionUrl = "/"+language+"" + entries[selEntrieId].actionurl;
										$('#global-searchinput').val('');
										
										//alert('offerbox.js actionUrl:' + actionUrl);
										$('#' + searchFormId).get(0).setAttribute('action', actionUrl);										
									}
									//$('#' + searchFormId).setAttribute('action', actionUrl); 
									$('#' + searchFormId).submit();
									
								}
							})
						} else {
							return false;
						}
						
					}
	});

}

function trim (myString)
{
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
//show and hide description in store 
function animate_text(){
	
		if($('p.description').height()==57){
			if($('p.description').height()<$('p.description span').height()){
				$('p.description').animate({height:$('p.description span').height()},'fast');			
			}
		}else if($('p.description').height()>57){
			$('p.description').animate({height:57},'fast');			
		}
	
	//alert($('p.description').height());
}
