/*
         global.js (by Luis Merino).
*/

// Globals and Constants
    var MAX_FONT = 1.25;
    var MIN_FONT = 1;
    var LIMIT_FONT = MIN_FONT;
    
// inicialize values
    Window.onDomReady(function(){
        textChange = new fx.Style('content', 'font-size', {unit: 'em', duration: 500, transition: Fx.Transitions.sineInOut});
        rememberTextChange();
        // search label init.
        setTimeout(initOverLabels, 50);  
    });
    
    function rememberTextChange() {
        var cookie = Cookie.get("textChange"); // Return the text size
        
        if (cookie) { // if there's a cookie
            textChange.set(cookie); // asign font size from cookie value
            LIMIT_FONT = cookie;    // so... target the new font size limit
        }
    }
	
	function resizeSidebar() {
		//  adjust sidebar height relative to the content height (faux columns) - IE 7 anchor fix.
		var contentHeight = document.getElementById('content').offsetHeight;
		var sidebarHeight = document.getElementById('sidebar').offsetHeight;

		if (contentHeight > sidebarHeight) {
			document.getElementById('sidebar').style.height = contentHeight;
		}
	}
    
// GLOBAL ONLOAD
    window.onload = function() {
        // Text Resize
        $('sizeUp').addEvent('click', function(){
            if(LIMIT_FONT < MAX_FONT) {
                textChange.custom(MIN_FONT,MAX_FONT);
                LIMIT_FONT = MAX_FONT;
                Cookie.set("textChange", MAX_FONT);
            }
        });
        $('sizeDown').addEvent('click', function(){
            if(LIMIT_FONT > MIN_FONT)
                textChange.custom(MAX_FONT,MIN_FONT);
                LIMIT_FONT = MIN_FONT;
                Cookie.set("textChange", MIN_FONT);
        });
        
        // initialization of BrowserDetect object
        BrowserDetect.init();        
        // check wheter is IE and its version 7 too
        if (BrowserDetect.browser != 'Explorer') return;
        if (BrowserDetect.version == '7') {
		
            resizeSidebar();
			
        } else if (BrowserDetect.version <= '6') {
            if (!document.getElementById('products')) return;
            var products = document.getElementById('products').getElementsByTagName('img');
            for (var i=0; i< products.length; i++) { /* three times 'for loop' because IE6 doesn't get the entire array once, what's wrong with you Gates? */
                if ( products[i].src.indexOf( '.png' ) != -1) {
                    fixPNG(products[i]);
                }
            }
            for (var i=0; i< products.length; i++) {
                if ( products[i].src.indexOf( '.png' ) != -1) {
                    fixPNG(products[i]);
                }
            }
            for (var i=0; i< products.length; i++) {
                if ( products[i].src.indexOf( '.png' ) != -1) {
                    fixPNG(products[i]);
                }
            }
        }
    }

    function initOverLabels () {
      if (!document.getElementById) return;      

      var labels, id, field;

      // Set focus and blur handlers to hide and show 
      // labels with 'overlabel' class names.
      labels = document.getElementsByTagName('label');
      for (var i = 0; i < labels.length; i++) {

        if (labels[i].className == 'overlabel') {

          // Skip labels that do not have a named association
          // with another field.
          id = labels[i].htmlFor || labels[i].getAttribute('for');
          if (!id || !(field = document.getElementById(id))) {
            continue;
          } 

          // Change the applied class to hover the label 
          // over the form field.
          labels[i].className = 'overlabel-apply';

          // Hide any fields having an initial value.
          if (field.value !== '') {
            hideLabel(field.getAttribute('id'), true);
          }

          // Set handlers to show and hide labels.
          field.onfocus = function () {
            hideLabel(this.getAttribute('id'), true);
          };
          field.onblur = function () {
            if (this.value === '') {
              hideLabel(this.getAttribute('id'), false);
            }
          };

          // Handle clicks to label elements (for Safari).
          labels[i].onclick = function () {
            var id, field;
            id = this.getAttribute('for');
            if (id && (field = document.getElementById(id))) {
              field.focus();
            }
          };

        }
      }
    };

    function hideLabel (field_id, hide) {
      var field_for;
      var labels = document.getElementsByTagName('label');
      for (var i = 0; i < labels.length; i++) {
        field_for = labels[i].htmlFor || labels[i].getAttribute('for');
        if (field_for == field_id) {
          labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
          return true;
        }
      }
    }

/*
    Browser Detection script
    Thanks to PPK on http://www.quirksmode.org/js/detect.html
    NOTE: reduced version, only for IE
*/
    var BrowserDetect = {
    	init: function () {
    		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    		this.version = this.searchVersion(navigator.userAgent)
    			|| this.searchVersion(navigator.appVersion)
    			|| "an unknown version";
    	},
    	searchString: function (data) {
    		for (var i=0;i<data.length;i++)	{
    			var dataString = data[i].string;
    			var dataProp = data[i].prop;
    			this.versionSearchString = data[i].versionSearch || data[i].identity;
    			if (dataString) {
    				if (dataString.indexOf(data[i].subString) != -1)
    					return data[i].identity;
    			}
    			else if (dataProp)
    				return data[i].identity;
    		}
    	},
    	searchVersion: function (dataString) {
    		var index = dataString.indexOf(this.versionSearchString);
    		if (index == -1) return;
    		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    	},
    	dataBrowser: [
    		{
    			string: navigator.userAgent,
    			subString: "MSIE",
    			identity: "Explorer",
    			versionSearch: "MSIE"
    		}
        ]
    };

// Fix PNG for IE
    function fixPNG(myImage){
        var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
        var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
        var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
        var imgStyle = "display:inline-block;" + myImage.style.cssText
        var strNewHTML = "<span " + imgID + imgClass + imgTitle
        strNewHTML += " style=\"" + "width:" + myImage.width + "px; height:" + myImage.height + "px;" + imgStyle + ";"
        strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
        strNewHTML += "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>" 
        myImage.outerHTML = strNewHTML
    }
    
// Emulation for Pseudo-classes in IE6
    function suckerfish(type, tag, parentId) {
        if (window.attachEvent) {
            window.attachEvent("onload", function() {
                var sfEls = (parentId==null)?document.getElementsByTagName(tag):document.getElementById(parentId).getElementsByTagName(tag);
                type(sfEls);
            });
        }
    }
// HOVER
    sfHover = function(sfEls) {
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
    }
// FOCUS
    sfFocus = function(sfEls) {
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onfocus=function() {
                this.className+=" sffocus";
            }
            sfEls[i].onblur=function() {
                this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
            }
        }
    }
// ACTIVE
    sfActive = function(sfEls) {
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmousedown=function() {
                this.className+=" sfactive";
            }
            sfEls[i].onmouseup=function() {
                this.className=this.className.replace(new RegExp(" sfactive\\b"), "");
            }
        }
    }
// TARGET
    sfTarget = function(sfEls) {
        var aEls = document.getElementsByTagName("A");
        document.lastTarget = null;
        for (var i=0; i<sfEls.length; i++) {
            if (sfEls[i].id) {
                if (location.hash==("#" + sfEls[i].id)) {
                    sfEls[i].className+=" sftarget";
                    document.lastTarget=sfEls[i];
                }
                for (var j=0; j<aEls.length; j++) {
                    if (aEls[j].hash==("#" + sfEls[i].id)) aEls[j].targetEl = sfEls[i];
                    aEls[j].onclick = function() {
                        if (document.lastTarget) document.lastTarget.className = document.lastTarget.className.replace(new RegExp(" sftarget\\b"), "");
                        if (this.targetEl) this.targetEl.className+=" sftarget";
                        document.lastTarget=this.targetEl;
                        return true;
                    }
                }
            }
        }
    }
	
	function writeFlash (cadena) {
	document.write(cadena);	
}

    suckerfish(sfFocus, 'TEXTAREA', 'content');
    suckerfish(sfFocus, 'INPUT', 'content');
	
	
	
function testSyndicationForm() {
	
	//valido el nombre
    if (document.RSS_form.nombre.value.length==0){
       alert("Please, fill in the Name field")
       document.RSS_form.nombre.focus()
       return false;
    } 
	
	//valido el apellido
    if (document.RSS_form.apellido.value.length==0){
       alert("Please, fill in the Surname field")
       document.RSS_form.apellido.focus()
       return false;
    } 
	
	//valido el e-mail
    if (document.RSS_form.email.value.length==0){
       alert("Please, fill in the Email field")
       document.RSS_form.email.focus()
       return false;
    } 
	
	//valido el puesto
    if (document.RSS_form.puesto.value.length==0){
       alert("Please, fill in the Workplace field")
       document.RSS_form.puesto.focus()
       return false;
    } 
	
	//valido el ciudad
    if (document.RSS_form.ciudad.value.length==0){
       alert("Please, fill in the City field")
       document.RSS_form.ciudad.focus()
       return false;
    } 
	
	//valido el pais
    if (document.RSS_form.pais.value.length==0){
       alert("Please, fill in the Country field")
       document.RSS_form.pais.focus()
       return false;
    } 
	
}

function checkLang() {
		if(readCookie('httpLang')) {
				var theLang=readCookie('httpLang');
		}else{
			if(document.all) {
				theLang=navigator.browserLanguage.substring(0,2).toLowerCase();
			}else{
				theLang=navigator.language.substring(0,2).toLowerCase();
			}
		}
		/*
		
		-> REVERT ME! I'M A HACK!
		
		setLang('es');*/
		setLang(theLang);
		
	}
//---------------------------------------------------
/*function setLang(idioma,url){
	alert(url);
	alert(idioma);
	document.miform.action=url;
	document.miform.idioma.value=idioma;
	document.miform.submit();
}*/

//---------------------------------------------------

	function setLang(l,x) {
		//deleteCookie('lang');
		saveCookie('lang',l,666);			
		location=location.href.replace(x);
	
	}
	
	
	/*
		Cookie Recipes
	*/

	function saveCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}else expires = "";
			document.cookie = name+"="+value+expires+"; path=";
		
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i<ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function deleteCookie(name) {
		saveCookie(name,"",-1);
	}
