/* =================================================================================

   Eginfor Informática JS
   Última Actualización: 20 Marzo, 2006

================================================================================= */

	// Default link-target preference. What should be default for new users?
	// Value true opens in _blank by default, false opens in _top by default
	var open_blank_default = false;
	
	// Website title - used only for cookie name to prevent cookie conflicts with other sites using this
	// No spaces, no special characters, just a unique name
	var site_title = "wishingline";
// END Configuration

// Cookie Functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var 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 eraseCookie(name) {
	createCookie(name,"",-1);
}
// Checkbox Loader
function loadLinkPrefs () {
	if (readCookie(site_title+"_linkprefs_cookie")) {
		initVal = readCookie(site_title+"_linkprefs_cookie");	// Load cookied preference
	} else {
		createCookie(site_title+"_linkprefs_cookie", true, 20000)
		initVal = open_blank_default;	// If no cookie is set
	}
	openBlank = initVal;
	setCheckbox(eval(initVal))
}
// Set Checkbox State
function setCheckbox(state) {
	openBlank = state;
	document.getElementById('linkprefs').checked = state;
	setTargets();
	createCookie(site_title+"_linkprefs_cookie", state, 20000)
}
// Configure Link Targets
function setTargets() {
	var link, l = 0;
	if (openBlank == true) {
		while (link = document.links[l++]) {
			// Open in _blank, except all links starting with...
			if (link.href.indexOf(url_1) == -1 && link.href.indexOf(url_2) == -1 && link.href.indexOf('javascript') == -1) link.target = '_blank'; 
		}
	} else {
		while (link = document.links[l++]) {
			// Open in _top, except all links starting with...
			if (link.href.indexOf(url_1) == -1 && link.href.indexOf(url_2) == -1 && link.href.indexOf('javascript') == -1) link.target = '_top'; 
		}
	}
}
// Event Listener, by Scott Andrew
function addEvent(obj, evType, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	} else {
		return false;
	}
}


/* ============================================================================== */
/* PNG Image Filter for Windows IE */
if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent)
	window.attachEvent("onload", pngLoadPngs);

// parses all images //public
function pngLoadPngs()
{
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);

	if (itsAllGood)
		for (var i = 0; i < document.images.length; i++)
			pngLoad(document.images[i]);
}

// loads an image, src is optional // public
function pngLoad(img,src)
{
	if (typeof img == "object" && typeof img.tagName == "string" && img.tagName == "IMG")
	{
		// this is an image
		if (typeof src == "string")
		{
			// src parameter is present
			if (src.match(/\.png$/i) != null)
			{
				// this is png image
				img.style.width = null;
				img.style.height = null;
				img.style.filter = null;
				img.src = src;
				pngSwapPrepare(img);
			}
			else
			{
				// its not a png
				img.src = src;
			}
		}
		else if (img.src.match(/\.png$/i) != null)
		{
				// no src arameter, but its png -> simply swap
				pngSwapPrepare(img);
		}
	}

	// swap (if complete) or shedule it to onload event // private
	function pngSwapPrepare(img)
	{
		if (img.complete)
			pngSwap(img);
		else
			img.attachEvent("onload",pngOnLoadSwap);
	}
	
	// supposed to be called when image is loaded into memory //private
	function pngOnLoadSwap()
	{
		event.srcElement.detachEvent("onload",pngOnLoadSwap);
		pngSwap(event.srcElement)
	}

	// Swaps img and background //private
	function pngSwap(img)
	{
		with (img)
		{
			style.width = width + "px";
			style.height = height + "px";
			style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale') "
			src = "http://www.wishingline.com/images/null.gif";
		}
	}
}


/* ============================================================================== */
/* Livesearch */
/*
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an "AS IS" BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: Bitflux GmbH <devel@bitflux.ch>                              |
// +----------------------------------------------------------------------+
*/

var liveSearchReq = false;
var t = null;
var liveSearchLast = "";
var isIE = false;

// on !IE we only have to initialize it once
if (window.XMLHttpRequest) {
	liveSearchReq = new XMLHttpRequest();
}

function liveSearchInit() {
	if (navigator.userAgent.indexOf("Safari") > 0) {
		document.getElementById('livesearch').addEventListener("keydown",liveSearchKeyPress,false);
	} else if (navigator.product == "Gecko") {
		document.getElementById('livesearch').addEventListener("keypress",liveSearchKeyPress,false);
	} else {
		document.getElementById('livesearch').attachEvent('onkeydown',liveSearchKeyPress);
		isIE = true;
	}
}

function liveSearchKeyPress(event) {
	if (event.keyCode == 40 )
	//KEY DOWN
	{
		highlight = document.getElementById("searchhighlight");
		if (!highlight) {
			highlight = document.getElementById("searchresult").firstChild.firstChild.nextSibling.nextSibling.firstChild;
		} else {
			highlight.removeAttribute("id");
			highlight = highlight.nextSibling;
		}
		if (highlight) {
			highlight.setAttribute("id","searchhighlight");
		} 
		if (!isIE) { event.preventDefault(); }
	} 
	//KEY UP
	else if (event.keyCode == 38 ) {
		highlight = document.getElementById("searchhighlight");
		if (!highlight) {
			highlight = document.getElementById("searchhighlight").firstChild.firstChild.nextSibling.nextSibling.lastChild;
		} 
		else {
			highlight.removeAttribute("id");
			highlight = highlight.previousSibling;
		}
		if (highlight) {
				highlight.setAttribute("id","searchhighlight");
		}
		if (!isIE) { event.preventDefault(); }
	} 
	//ESC
	else if (event.keyCode == 27) {
		highlight = document.getElementById("searchhighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		document.getElementById("searchresult").style.display = "none";
		document.forms.searchform.s.value = '';
	} 
}

function closeLiveSearch() {
	highlight = document.getElementById("searchhighlight");
	if (highlight) {
		highlight.removeAttribute("id");
	}
	document.getElementById("searchresult").style.display = "none";
	document.forms.searchform.s.value = '';
}

function liveSearchStart() {
	if (t) { window.clearTimeout(t); }
	t = window.setTimeout("liveSearchDoSearch()",200);
}

function liveSearchDoSearch() {
	if (liveSearchLast != document.forms.searchform.s.value) {
	if (liveSearchReq && liveSearchReq.readyState < 4) {
		liveSearchReq.abort();
	}
	if ( document.forms.searchform.s.value == "") {
		document.getElementById("searchresult").style.display = "none";
		highlight = document.getElementById("searchhighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		return false;
	}
	if (window.XMLHttpRequest) {
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	liveSearchReq.onreadystatechange= liveSearchProcessReqChange;
	liveSearchReq.open("GET","./livesearch.php?s=" + document.forms.searchform.s.value);
	liveSearchLast = document.forms.searchform.s.value;
	liveSearchReq.send(null);
	}
}

function liveSearchProcessReqChange() {
	if (liveSearchReq.readyState == 4) {
		var  res = document.getElementById("searchresult");
		res.style.display = "block";
		res.firstChild.innerHTML = '<div id="searchcontrols"><div class="left">tip: use arrow keys + enter</div><div class="right"><a href="javascript://" title="Close results" onclick="closeLiveSearch();">close (esc)</a></div><br /></div><div id="searchheader">top search results:</div>'+liveSearchReq.responseText;
		 
	}
}

function liveSearchSubmit() {
	var highlight = document.getElementById("searchhighlight");
	if (highlight && highlight.firstChild) {
		window.location = highlight.firstChild.getAttribute("href");
		return false;
	} else {
		return true;
	}
}

function closeResults() {
    document.getElementById("searchresult").style.display = "none";
}


/* ============================================================================== */
/* Unobtrusive JS Window Popups */
var popupLinkConfig = new Array;

// popupLinkConfig["classname"] = new Array ( "targetname", "width=550,height=350,scrollbars=yes,resizable=yes,status=yes,toolbar=yes,location=yes,menubar=yes");
popupLinkConfig["popup"]    = new Array ( "", "width=350,height=450,scrollbar=yes,menubar=yes");
popupLinkConfig["glossary"] = new Array ( "help", "width=550,height=350,resizable=yes");

popupLinkConfig["gallery"] = new Array("gallery","width=814,height=400,0,0,scrollbars=no,status=yes,menubar=yes,toolbar=no,resizable=no");
popupLinkConfig["example"] = new Array("example","width=640,height=480,resizable=no");
popupLinkConfig["screenshot"] = new Array("screenshot","width=1199,height=828,0,0,status=yes,menubar=no,toolbar=no,resizable=yes");
popupLinkConfig["largepreview"] = new Array("largepreview","width=1024,height=768,0,0,status=no,menubar=no,toolbar=no,resiable=yes");
popupLinkConfig["videowindow"] = new Array("videowindow","width=640,height=480,0,0,status=yes,menubar=no,toolbar=no,resiable=yes");
popupLinkConfig["masterfilerebranding"] = new Array("masterfilerebranding","width=832,height=456,0,0,status=yes,menubar=no,toolbar=no,resizable=yes");
popupLinkConfig["katklock"] = new Array("katklock","width=300,height=400,0,0,status=yes,menubar=yes,location=no,toolbars=no,resizable=yes");
popupLinkConfig["smallwin"] = new Array("smallwin","width=424,height=464,0,0,scrollbars=yes,status=yes,menubar=no,toolbar=no,resizable=no");

function initPopupLinks() {
  if (!document.getElementsByTagName) return true;
  var pageLinks = document.getElementsByTagName("a");
  for (var i = 0; i < pageLinks.length; i++) {
    if (((pageLinks[i].className != null) && 
         (pageLinks[i].className != "")) ||
        ((pageLinks[i].parentNode.className != null) && 
         (pageLinks[i].parentNode.className != ""))) {
      var linkClass = " " + pageLinks[i].className + " ";
      if ((linkClass == "  ") && (pageLinks[i].parentNode.className != "")) {
        linkClass = " " + pageLinks[i].parentNode.className + " ";
      }
      for (var theKey in popupLinkConfig)  {
        if (linkClass.indexOf(" " + theKey + " ") > -1) {
          if ((pageLinks[i].target == "") || (pageLinks[i].target == null)) {
            pageLinks[i].target = (popupLinkConfig[theKey][0] != "") ? popupLinkConfig[theKey][0] : theKey;
          }
          pageLinks[i].settings = popupLinkConfig[theKey][1];
          pageLinks[i].onclick = popUp;
        }
      }
    }
  }
  return true;
}

function popUp() {
  newWin = window.open(this.href, this.target, this.settings);
  newWin.focus();
  return false;
}


/* ============================================================================== */
/* Contact Form */
function enableOther() {
	if (document.contactus.asunto.selectedIndex != 4) {
		document.contactus.otros.value = "";
		document.contactus.otros.disabled = true;
		document.getElementById('label_otros').style.color = "#C9CCCF";
		return true;
	} else {
		//alert("Other field is now enabled");
		document.contactus.otros.disabled = false;
		document.getElementById('label_otros').style.color = "#989EA5";
		document.contactus.otros.focus();
		return false;
	}
}

function setState(obj_privacy,obj_submit) {
	if(obj_privacy.checked) {
		obj_submit.disabled = false;
	} else {
		obj_submit.disabled = true;
	}
}

function resetForm() {
	// Reset all form values and set the focus to the first field
	document.contactus.nombre.value = "";
	document.contactus.nombre.focus();

	document.contactus.apellidos.value = "";    
	document.contactus.email.value = "";
	document.contactus.otros.value = "";
	document.contactus.otros.disabled = true;
	document.getElementById('label_otros').style.color = "#C9CCCF";
	document.contactus.texto.value = "";
	/*document.contactus.privacy.value = "Yes";
	document.contactus.privacy.checked = false;
	document.contactus.company.value = "";
	document.contactus.address.value = "";
	document.contactus.city.value = "";
	document.contactus.state.value = "";
	document.contactus.zip_code.value = "";
	document.contactus.tel.value = "";
	document.contactus.countries.selectedIndex = 0;*/
	document.contactus.asunto.selectedIndex = 0;
}

function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
		var element = document.getElementById(expandCollapse.arguments[i]);
		element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}

/* ============================================================================== */
/* Generic onload Function - allows more than one function to be called */
function generic() {
	// Set the main window/tab name
	windowTitle="wish_main";
	window.name = windowTitle;
	// alert("Window Name is: " + windowTitle);
	// Fires first, then body onload
	initPopupLinks();
	// Load the non-invasive JS popup window functionality
}

// Setup onload function
if(typeof window.addEventListener !='undefined') {
	// ...Gecko, Safari, Konqueror, and Standard
	window.addEventListener('load',generic,false);
} else if(typeof document.addEventListener !='undefined') {
	// ...Opera 7
	document.addEventListener('load',generic,false);
} else if(typeof window.attachEvent != 'undefined') {
	// ...Win/IE
	window.attachEvent('onload',generic);
} else {
	// ...Mac IE5 and anything else
	// Ifthere's an existing onload function
	if(typeof window.onload == 'function') {
		// Call existing onload function
		existing();
		
		// Call generic onload function
		generic();
	} else {
		// Setup onload function
		window.onload = generic;
	}
}

/* ============================================================================== */
/* Run Functions: onload */
function init() {
    liveSearchInit(); // Initialize Livesearch
    //alert("Livesearch initialized");
}

/* Simple Client-Side Form Validation */
function validateForm(myForm) {
    var requiredFields = myForm.nochoice.value.split("|");
    var errorString = '';
    for (var i=0; i<requiredFields.length; i++) {
        var parts = requiredFields[i].split(",");
        var field = parts[0]; var title = parts[1];
        for (var j=0; j<myForm.elements.length; j++) {
            var myElement = myForm.elements[j];
            var isNull = false;
            if (myElement.name == field && myElement.style.display != "none") {
                if (myElement.type == "select-one" || myElement.type == "select-multiple") {
                    if ((myElement.options[myElement.selectedIndex].value == null || myElement.options[myElement.selectedIndex].value == '') && errorString.indexOf(title) == -1) {
                        isNull = true;
                    }
                } else if ((myElement.value == null || myElement.value.search(/\w/) == -1) && errorString.indexOf(title) == -1) {
                    isNull = true;
                }

            if (isNull) {
                errorString += title + ", ";
                if (document.getElementById('label_'+myElement.name)) { 
                    document.getElementById('label_'+myElement.name).className="er"; }
                    myElement.className="erInput";
                } else {
                    if (document.getElementById('label_'+myElement.name)) {
                        document.getElementById('label_'+myElement.name).className="req";
                    }
                    myElement.className="req";
                }
            }
        }
    }
    if (errorString != '') {
        errorString = errorString.slice(0,errorString.length-2);
        window.alert("Por favor, antes de enviar los datos complete los campos requeridos:\n\n"+errorString)
        return false;
    }
    else {
        return true;
    }
}