
// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode( )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	document.URLForm.F2.value = encoded;
  document.URLForm.F2.select();
	return false;
};

function URLDecode( )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   document.URLForm.F1.value = plaintext;
   document.URLForm.F1.select();
   return false;
};



//submita un form para modalbox!
function submitForm(url,obj){
		var params2Submit = '';
		for (var i=0; i < obj.elements.length; i++) {
 		  var element = obj.elements[i];
 		  if(i>0)
 		  	params2Submit+='&';
 		  params2Submit+=element.name+'='+element.value;
 			
		}
		var finalUrl = url;
		if(i>0)
			finalUrl += '?'+params2Submit;
		Modalbox.show('Completa', finalUrl , {});
		return false;
	}


function validateInt()
    {
        var o = document.frmInput.txtInput;
        switch (isInteger(o.value))
        {
            case true:
                alert(o.value + " is an integer")
                break;
            case false:
                alert(o.value + " is not an integer")
        }
    }

   function validateRange()
   {
        var s = document.frmInput.txtInput.value;
        var A = document.frmInput.txtA.value;
        var B = document.frmInput.txtB.value;

        switch (isIntegerInRange(s, A, B))
        {
            case true:
                alert(s + " is in range from " + A + " to " + B)
                break;
            case false:
                alert(s + " is not in range from " + A + " to " + B)
        }
   }

// isIntegerInRange (STRING s, INTEGER a, INTEGER b)
   function isIntegerInRange (s, a, b)
   {   if (isEmpty(s))
         if (isIntegerInRange.arguments.length == 1) return false;
         else return (isIntegerInRange.arguments[1] == true);

      // Catch non-integer strings to avoid creating a NaN below,
      // which isn't available on JavaScript 1.0 for Windows.
      if (!isInteger(s, false)) return false;

      // Now, explicitly change the type to integer via parseInt
      // so that the comparison code below will work both on
      // JavaScript 1.2 (which typechecks in equality comparisons)
      // and JavaScript 1.1 and before (which doesn't).
      var num = parseInt (s);
      return ((num >= a) && (num <= b));
   }

    function isInteger (s)

    {
        var i;

        if (isEmpty(s))
             if (isInteger.arguments.length == 1) return 0;
             else return (isInteger.arguments[1] == true);

         for (i = 0; i < s.length; i++)
         {
              var c = s.charAt(i);

              if (!isDigit(c)) return false;
         }

         return true;
    }

    function isEmpty(s)
    {
        return ((s == null) || (s.length == 0))
    }

    function isDigit (c)
    {
        return ((c >= "0") && (c <= "9"))
    }

    function isSignedInteger (s)

    {   if (isEmpty(s))
             if (isSignedInteger.arguments.length == 1) return false;
             else return (isSignedInteger.arguments[1] == true);

         else {
              var startPos = 0;
              var secondArg = false;

              if (isSignedInteger.arguments.length > 1)
                    secondArg = isSignedInteger.arguments[1];

              // skip leading + or -
              if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
                  startPos = 1;
              return (isInteger(s.substring(startPos, s.length), secondArg))
         }
    }

    function isPositiveInteger (s)
    {   var secondArg = false;

         if (isPositiveInteger.arguments.length > 1)
              secondArg = isPositiveInteger.arguments[1];

         // The next line is a bit byzantine.  What it means is:
         // a) s must be a signed integer, AND
         // b) one of the following must be true:
         //    i)  s is empty and we are supposed to return true for
         //        empty strings
         //    ii) this is a positive, not negative, number

         return (isSignedInteger(s, secondArg)
                && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) );
    }

    function isNonnegativeInteger (s)
    {   var secondArg = false;

         if (isNonnegativeInteger.arguments.length > 1)
              secondArg = isNonnegativeInteger.arguments[1];

         // The next line is a bit byzantine.  What it means is:
         // a) s must be a signed integer, AND
         // b) one of the following must be true:
         //    i)  s is empty and we are supposed to return true for
         //        empty strings
         //    ii) this is a number >= 0

         return (isSignedInteger(s, secondArg)
                && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
    }

    function setTitle()
    {
        var actionNeeded = 0;
        if (window.parent) {
            if (window.parent.frames.length) {
                if (window.parent.frames["TitleFrame"].setTitle)
                    window.parent.frames["TitleFrame"].setTitle("JavaScript Tips");
            }


                if (actionNeeded==1 || !window.parent.frames.length) {

                    if (oBrowser.nsOld)
                        document.show.brw.value="nsold"
                    else if (oBrowser.opera)
                        document.show.brw.value="opera"
                    else if (oBrowser.ie)
                        document.show.brw.value="ie"
                    else if (oBrowser.nsNew)
                        document.show.brw.value="nsnew"
                    else
                        document.show.brw.value="unknown"
                    document.show.submit();
                }
            }
    }

function quitaChar(str,ch){
	return str.replace(ch,'')

}

function reemplazarStr(string, text, by){

	// Replaces text with by in string
	var strLength = string.length, txtLength = text.length;
	if ((strLength == 0) || (txtLength == 0)) return string;

	var i = string.indexOf(text);
	if ((!i) && (text != string.substring(0,txtLength))) return string;
	if (i == -1) return string;

	var newstr = string.substring(0,i) + by;

	if (i+txtLength < strLength)
	newstr += reemplazarStr(string.substring(i+txtLength,strLength),text,by);

	return newstr;

}

/*
function URLEncode(toEncode)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
	"abcdefghijklmnopqrstuvwxyz" +
	"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = toEncode;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
			encoded += ch;
		} else {
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				alert( "Unicode Character '"
				+ ch
				+ "' cannot be encoded using standard URL encoding.\n" +
				"(URL encoding only supports 8-bit characters.)\n" +
				"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode( toDecode)
{
	// Replace + with ' '
	// Replace %xx with equivalent character
	// Put [ERROR] in output if %xx is invalid.
	var HEXCHARS = "0123456789ABCDEFabcdef";
	var encoded = toDecode;
	var plaintext = "";
	var i = 0;
	while (i < encoded.length) {
		var ch = encoded.charAt(i);
		if (ch == "+") {
			plaintext += " ";
			i++;
		} else if (ch == "%") {
			if (i < (encoded.length-2)
			&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
			&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
			plaintext += ch;
			i++;
		}
	} // while
	return plaintext;
};

*/
/*
*   En función de si state es true o false, hace un blindUp o blinddown de la caja con id id
* 	requiere que se incluyan los siguientes scripts:
*	<script type="text/javascript" src="/sf/prototype/js/builder.js"></script>
*	<script type="text/javascript" src="/sf/prototype/js/effects.js"></script>
*/
function toggleBlind(state,id){
	if(state)
	Effect.BlindDown(id, {});
	else
	Effect.BlindUp(id, {});
}


/*
*   Element es el id del elemento interruptor, y id es el id del elemento que queremos que cambie de estado.
* 	requiere que se incluyan los siguientes scripts:
*	<script type="text/javascript" src="/sf/prototype/js/builder.js"></script>
*	<script type="text/javascript" src="/sf/prototype/js/effects.js"></script>
*/
function toggleDisable(id2,id){
	var objhor = $(id+'_hour');
	var objmin = $(id+'_minute');
	if($F(id2)){
		objhor.enable();
		objmin.enable();
	}else{
		objhor.disable();
		objmin.disable();
	}

}



/*
* Permite que al presionar enter se submite un formulario
*
*/
function submitenter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		new Ajax.Updater({success:'sf_guard_auth_form'}, '/index.php/login', {asynchronous:true, evalScripts:true, parameters:Form.serialize(myfield.form)});
		myfield.form.submit();
		return false;
	}
	else
	return true;
}

function submitenterAjax(myfield,e,urlto)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		//new Ajax.Updater({success:'sf_guard_auth_form'}, '/index.php/login', {asynchronous:true, evalScripts:true, parameters:Form.serialize(myfield.form)});
		new Ajax.Updater('mensaje_emergente_contenido', urlto, {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;
		myfield.form.submit();
		return false;
	}
	else
	return true;
}


function showMsg(id,msg){
	
}

function hideMsg(id){
}

/*
* permite crear un mensaje que aparezca cerca del mouse
* y lo sigue durante un tiempo hasta que desaparece
*
*/
/*
var offsetfrommouse=[10,10];
currentimageheight = 45;
itemWidth=70;

mensajes=0;

function truebody(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function mueve(){
	mensajes++;

	if (mensajes==1){
		document.onmousemove=followmouse;
	}
}

function para(){
	mensajes--;
	if(mensajes == 0)
	document.onmousemove="";
}

function showMsg(id,msg){
	if(msg!=undefined){
		gettrailobjnostyle(id).innerHTML = msg;
	}
	mueve();
	Element.show(id);
	gettrailobj(id).visibility="visible";
}

function hideMsg(id){
	Element.hide(id);
	para();
	gettrailobj(id).visibility="hidden";
}

function gettrailobj(id){
	if (document.getElementById)
	return document.getElementById(id).style
	else if (document.all)
	return document.all.id.style
}

function gettrailobjnostyle(id){
	if (document.getElementById)
	return document.getElementById(id)
	else if (document.all)
	return document.all.id
}

function followmouse(e){

	var xcoord=offsetfrommouse[0]
	var ycoord=offsetfrommouse[1]

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(document.body.offsetHeight, window.innerHeight)

	if (typeof e != "undefined"){
		if (docwidth - e.pageX < itemWidth){
			xcoord = e.pageX - xcoord - itemWidth; // Move to the left side of the cursor
		} else {
			xcoord += e.pageX;
		}
		if ((docheight - e.pageY) < (currentimageheight + 10)){
			ycoord += e.pageY - Math.max(0,(10 + currentimageheight + e.pageY - docheight - truebody().scrollTop));
		} else {
			ycoord += e.pageY;
		}
	} else if (typeof window.event != "undefined"){
		if (docwidth - event.clientX < itemWidth){
			xcoord = event.clientX + truebody().scrollLeft - xcoord - itemWidth; // Move to the left side of the cursor
		} else {
			xcoord += truebody().scrollLeft+event.clientX
		}
		if (docheight - event.clientY < (currentimageheight + 10)){
			ycoord += event.clientY + truebody().scrollTop - Math.max(0,(10 + currentimageheight + event.clientY - docheight));
		} else {
			ycoord += truebody().scrollTop + event.clientY;
		}
	} else{
		xcoord += e.pageX;
		ycoord += e.pageX;
	}

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.max(truebody().scrollHeight, truebody().clientHeight) : Math.max(document.body.offsetHeight, window.innerHeight)

	gettrailobj('missatge').left=xcoord+"px"
	gettrailobj('missatge').top=ycoord+"px"

	gettrailobj('missatge2').left=xcoord+"px"
	gettrailobj('missatge2').top=ycoord+"px"
}
*/

var timer;
var timer_peticion;
var timer_producto;

//dropdown menu
$j(document).ready(function(){
	$j("#menu_top ul:first li").hover(function(){
	   $j(this).addClass("hover");
	   $j('> .dir',this).addClass("open");
	   $j('ul:first',this).css('visibility', 'visible');
	},function(){
	   $j(this).removeClass("hover");
	   $j('.open',this).removeClass("open");
	   $j('ul:first',this).css('visibility', 'hidden');
	});
	
	$j("#menu_top ul:first li ul li").hover(function(){
	   $j(this).addClass("hover");
	   $j('> .dir',this).addClass("open");
	   $j('ul:first',this).css('visibility', 'visible');
	},function(){
	   $j(this).removeClass("hover");
	   $j('.open',this).removeClass("open");
	   $j('ul:first',this).css('visibility', 'hidden');
	});
		
	$j("#userMenuTop").hover(function(){
		$j("#user_login_info").css('display','block');		
	},function(){
		$j("#user_login_info").css('display','none');
	});
	
	/* change the style of the select and add default text */
	$j("#type").select_skin();
    $j(".defaultText").focus(function(srcc){
        if ($j(this).val() == $j(this)[0].title)
        {
            $j(this).removeClass("defaultTextActive");
            $j(this).val("");
        }
    });
    
    $j(".defaultText").blur(function(){
        if ($j(this).val() == "")
        {
            $j(this).addClass("defaultTextActive");
            $j(this).val($j(this)[0].title);
        }
    });
    
    $j(".defaultText").blur();
    
    /* jQuery Flash Plugin - Flash Text-Replacement (sIFR) */
    $j('h2').sifr({path: '/swf/', font: 'trebuchet_ms'})
    $j('.lateral_esquerra h3').sifr({path: '/swf/', font: 'trebuchet_ms'})
    $j('#pidelo').sifr({path: '/swf/', font: 'trebuchet_ms', color: "#FFFFFF"})
    $j('#ofrecelo').sifr({path: '/swf/', font: 'trebuchet_ms'})
});
