$(function(){
    //On form submit
	$('form').submit(function() {
		var formId 	 = $(this).attr('id');
		var formName = $(this).attr('name');
		var formData = $(this).serialize();
		
		$.ajax({
			url: "modules/xf_"+formName+'.php',
			data: formData,
			type: 'POST',
			success: function(msg){
				if(msg=='ok'){
					$("#"+formId).slideUp(function(){
						$("#"+formId+'_Complete').show();					   
					});
				}else{
					alert(msg);
				}
			}
		});
		
		return false;
	});
    
    //Show rating on page load
    $('.starsDiv').each(function(i) {
        var id      = $(this).attr('id').replace('stars_','');
        var rating  = $(this).attr('rating');
        var link    = $(this).attr('rel');
        
        showRatingStars(id, rating, link);
    });
});


//Rewrite the search term
function rewriteSearch (term){
	if(term.length < 3){
		alert('Necesitas usar al menos 3 caracteres en tu búsqueda');
		return;
	}else{
		var new_term = term.replace(/ /g, "_");
			new_term = makeSafe(new_term)
			
		new_path = "s_"+new_term+".html";
		location.href = new_path;
	}
}

// Function for making sure text only uses url safe symbols
function makeSafe(thisText, allowSpace){
    var w = "!@#$%^&*()+=[]\\\';,./{}|\":<>?";
    var s = 'abcdefghijklmnopqrstuvwxyz0123456789-_';
    var x = new Array('àáâãäå', 'ç', 'èéêë', 'ìíîï', 'ñ', 'ðóòôõöø', 'ùúûü', 'ýÿ');
    var r = new Array('a', 'c', 'e', 'i', 'n', 'o', 'u', 'y');

    if(allowSpace){
    	s = s + ' ';
    }

    var newText = new Array();

    for (i = 0; i < thisText.length; i++){
   		thisChar = thisText.charAt(i);
        if(w.indexOf(thisChar) == -1){
            if(s.match(''+thisChar+'')){
                newText[i] = thisChar;
        	}else{
                for (j = 0; j < x.length; j++){
                    if(x[j].match(thisChar)){
                            newText[i] = r[j];
                    }
               	}
            }
        }
    }

    return newText.join('');
}


//Submit a form
function submitForm(formID){
	$('#'+formID).submit();
}


//Show Rating Stars (index page)
function showRatingStars(content_id,rating,href){
    
    if(href!=''){
    	var readOnly = true;
    	var hintList = ['', '', '', '', ''];
        var clicked  = function(){window.location.href = href};
    }else{
        var readOnly = false;
        var hintList = ['muy malo', 'malo', 'regulero', 'bueno', 'muy bueno'];
		var clicked  = function(score, evt) {
                        $.ajax({
                        	url: "modules/xf_savevote.php",
                        	data: ({score : score, id : content_id}),
                        	type: 'POST',
                        	success: function(msg){
                        		if(msg=='VOTED'){
                        			alert('Gracias por votar!');
                        		}else{
                        			alert(msg);
                        		}
                        	}
                        });
		              }     
    }
    
    
	$('#stars_'+content_id).raty({
		half:  		true,
		size:       20,
		scoreName:  'entity.score',
		start: 		rating,
		starOff:	'../images/star-off-big.png',
		starOn:		'../images/star-on-big.png',
		starHalf:	'../images/star-half-big.png',
		number:		5,
		readOnly:	readOnly,
		hintList:   hintList,
		click:      clicked
	}).width(145);
}
var openxAttributes={}
var openxDebugMode=0;
function openxAddVar(name,value)
{
	openxAttributes[name]=value
}
function openxGetVars()
{
	return openxAttributes;
}
function openxGetVarsAsQuery()
{
	var query="";
	for(var t in openxAttributes){
		query += t +"="+encodeURIComponent(openxAttributes[t])+"&";				
	}
	return query;
}
function openxWriteZone(id,preventContext)
{
	if(openxDebugMode){
		document.write("[[zone "+id+"]]");
	}
	var m3_u = (location.protocol=='https:'?'https://adsdelivery.envialo.es/ajs.php':'http://adsdelivery.envialo.es/ajs.php');
	var m3_r = Math.floor(Math.random()*99999999999);
	if (!document.MAX_used) document.MAX_used = ',';
	document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u);
	document.write ("?zoneid="+id+"&amp;target=_blank");
	document.write ('&amp;cb=' + m3_r);
	if (document.MAX_used != ',') document.write ("&amp;exclude=" + document.MAX_used);
//	document.write (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));
	document.write (document.charset ? '&amp;charset='+'utf-8' : (document.characterSet ? '&amp;charset='+'utf-8' : ''));
	document.write ("&amp;loc=" + escape(window.location));

	// Content channels
	for(k in openxAttributes){
		document.write ("&amp;"+escape(k)+"=" + escape( openxAttributes[k] ));
	}

	if (document.referrer) document.write ("&amp;referer=" + escape(document.referrer));
	// Disabled by ismael 11-may-2010, it fucks the zones in somes sites like xxxrasuradas.com
	if(!preventContext)
		if (document.context) document.write ("&amp;context=" + escape(document.context));
	if (document.mmm_fo) document.write ("&amp;mmm_fo=1");
	document.write ("'><\/scr"+"ipt>");
}

//Popunder
var puShown = false;

  function doOpen(url)
  {
          if ( puShown == true )
          {
                  return true;
          }
          var wFeatures = "toolbar=1,statusbar=1,resizable=1,scrollbars=1,menubar=1,location=1,directories=0";
          if(navigator.userAgent.indexOf('Chrome') != -1){
             wFeatures = "scrollbar=yes";
          }
          pu_window=  window.open('about:blank','wmPu',wFeatures +  ',height=768,width=1024');

          var regex = new RegExp(/rv:[2-9]/);
   if (regex.exec(navigator.userAgent)) {
       pu_window.ljPop = function (jsm_url) {

           if (regex.exec(navigator.userAgent)) { // Gecko 2+
                          this.window.open('about:blank').close();
                      }
                      this.document.location.href = url;
                  };
                  pu_window.ljPop(url);
              }
              else {
                  pu_window.document.location.href = url;
              }
              setTimeout(window.focus);
              window.focus();

           if(pu_window) {
               pu_window.blur();
               puShown = true;
            }

              return pu_window;
  }


  function setCookie(name, value, time)
  {
      var expires = new Date();

      expires.setTime( expires.getTime() + time );

      document.cookie = name + '=' + value + '; expires=' + expires.toGMTString();
  }


  function getCookie(name) {
      var cookies = document.cookie.toString().split('; ');
      var cookie, c_name, c_value;

      for (var n=0; n<cookies.length; n++) {
          cookie  = cookies[n].split('=');
          c_name  = cookie[0];
          c_value = cookie[1];

          if ( c_name == name ) {
              return c_value;
          }
      }

      return null;
  }


  function initPu()
  {
          if ( document.attachEvent )
          {
                  document.attachEvent( 'onclick', checkTarget );
          }
          else if ( document.addEventListener )
          {
                  document.addEventListener( 'click', checkTarget, false );
          }
  }


  function checkTarget(e)
  {
      if ( !getCookie('popundr') ) {
          var e = e || window.event;
          
          var sites = [ '/popunder/index.php?'+openxGetVarsAsQuery() ];
			    var site = sites[ Math.floor( Math.random()*sites.length) ];
          
          var win = doOpen(site);

          setCookie('popundr', 1, 24*60*60*1000);
      }
  }

initPu();
