function $(id) { return document.getElementById(id); }
function $c(name) { return document.createElement(name); }

var nn = (document.layers)? true:false;
var ms = (document.all)? true:false;
var n6 = (document.getElementById) ? true:false;


function checkSearch(form){
	//form = document.formsearch;
	if (trim(form["search-clause"].value) != "")
		return true
	else
		return false
}

function trim(lancuch){
	while (lancuch.charAt(0) == " ") 
		lancuch = lancuch.substring(1,lancuch.length);
	while (lancuch.charAt(lancuch.length-1) == " ") 
		lancuch = lancuch.substring(0,lancuch.length-2);
	return lancuch;	
}


function openWindow(file,szer,wys,scrollec){
	wys = (!wys)?(300):(wys);
	szer = (!szer)?(400):(szer);
	scrollec = (!scrollec)?('no'):('yes');
	if (ms) var xMax = screen.width, yMax = screen.height
	else if (nn) var xMax = window.outerWidth, yMax = window.outerHeight
	var xOffset = (xMax - szer)/2, yOffset = (yMax - wys)/2; 
	okienko = window.open(file,'TWTPop','scrollbars='+scrollec+',height='+wys+',width='+szer+',screenX='+xOffset+',screenY='+yOffset+',top='+yOffset+',left='+xOffset+',resizable=yes');
	okienko.focus();
}

function addParameter(href, param, value){
	if (href.indexOf("?") > -1)
		href += "&";
	else
		href += "?";
	
	return href + param + "=" + value;
}

function getClientSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight]
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}


/* ----------------------------------------------------------------------
	ADD EVENT
---------------------------------------------------------------------- */
function addEvent(obj, type, fn){
  if (obj.addEventListener){
    obj.addEventListener(type, fn, false);
  } else if (obj.attachEvent){
   	obj["e"+type+fn] = fn;
    obj[type+fn] = function(){obj["e"+type+fn](window.event);}
    obj.attachEvent("on"+type, obj[type+fn]);
  }
}

function aEL(o,t,f){
	var a=Array.prototype.slice.call(arguments,3)
	o[t+f]=function(e){return !1===f.apply(o,[e||window.event].concat(a))?e.preventDefault?e.preventDefault():!1:1}
	return(o.x=o.addEventListener)?o.x(t,o[t+f],!1):(o.x=o.attachEvent)?o.x('on'+t,o[t+f]):!1;
}


/*=============================================================================
    AJAX LIB
==============================================================================*/
function ajaxRequest(url, method, containerResponse, postFunction)
{
	var req;
	if(window.XMLHttpRequest)
		req = new XMLHttpRequest();
	else if(window.ActiveXObject)
		req = new ActiveXObject("Microsoft.XMLHTTP");
	
	// if browser doesn't support ajax return true
	if(!req)
		return false;
	
	req.open(method.toUpperCase(), url , true );
	
	// process function
 	req.onreadystatechange=function()
 	{
  		//alert("req.readyState = " + req.readyState + ", req.status = " + req.status);
 		if (req.readyState == 4) 
  			if(req.status == 200 || req.status == 301)
  			{
  				/*
  				 * readyState = 
  				 * 0: uninitialized
				 * 1: loading
				 * 2: loaded
				 * 3: interactive
				 * 4: complete
  				 * 
  				 * status= [use statusText]
				 * 200: "Ok"
				 * 301: "Moved Permanently"
				 * 304: "Not Modified" (page hasn't been modified)
				 * 404: "Not Found"
				 * 403: "Forbidden"
				 * 401: "Unauthorized" (wrong password)
				 */
  				containerResponse.innerHTML = req.responseText;
  				//alert(req.responseText);
  				if(postFunction) postFunction();
  			}
	}
	
	// send request
	req.send(null);
	
	return true;
}


/* ----------------------------------------------------------------------
	ZIP CODE
---------------------------------------------------------------------- */
function initZipFunctions(){
	var zipField = getZipFields();
	if (!zipField)
		return false;
	
	addEvent(zipField, "blur", tryZipCode);
	//addEvent(zipField, "keypress", tryZipCode);
}

function tryZipCode(){
	var zipField = getZipFields();
	if (!zipField)
		return false;
	
	var customerAddres = document.getElementById("customer_addres");
	if (!customerAddres){
		alert("Contact area does not exist");
		return;
	}
	
	var zipCode = zipField.value;
	//alert(zipCode);
	 
	var u = "/portlets/zip/zip_code.xml?zip=" + zipCode + "&service_address=" + getValue("id_service_address") + "&service_address2=" + getValue("id_service_address2") + "&service_city=" + getValue("id_service_city") + "&service_state=" + getValue("id_service_state");
	//alert(u);
	if (ajaxRequest(u, "get", customerAddres, afterTryZip))
		showZipPreloader("visible");
}
function getValue(fieldId){
	var f = document.getElementById(fieldId);
	if (!f)
		return "";
	
	return f.value;
}

function afterTryZip(){
	showZipPreloader("hidden");
	
	var service_address = document.getElementById("id_service_address");
	if (!service_address) return;
	//if it's empty, set cursor in address field 
	if(service_address.value=='') {
		service_address.focus();
	}
}

function getZipFields(){
	var zipField = document.getElementById("id_service_zip");
	if (!zipField)
		alert("ZIP fields does not exist");
	
	return zipField;
}

function showZipPreloader(v){
	var zipPreloader = document.getElementById("zip_preloader");
	if (!zipPreloader)
		return;
	
	zipPreloader.style.visibility = v;
}


/* ----------------------------------------------------------------------
	ONGOING SERVICE ongoing_service
---------------------------------------------------------------------- */
function initOngoingService(){
	var howOften1 = document.getElementById("id_schedule_type_1");
	var howOften2 = document.getElementById("id_schedule_type_2");
	//var howOften3 = document.getElementById("id_schedule_type_3");
	
	if (!howOften1 || !howOften2)
		return false;
	
	addEvent(howOften1, "click", ongoingServiceDeSelect);
	addEvent(howOften2, "click", ongoingServiceSelect);
	//addEvent(howOften3, "click", ongoingServiceDeSelect);
	//addEvent(zipField, "keypress", tryZipCode);
}

function ongoingServiceSelect(){
	//alert("Select")
	ongoingServiceDisplay("block");
}

function ongoingServiceDeSelect(){
	ongoingServiceDisplay("none");
}

function ongoingServiceDisplay(dis){
	var ongoingServiceSelect = document.getElementById("id_ongoing_service");
	if (!ongoingServiceSelect)
		return false;
	
	ongoingServiceSelect.style.display = dis;
}


/* ----------------------------------------------------------------------
	RECCYCLING ALERD reccycling_alerd
---------------------------------------------------------------------- */
function initReccyclingAlerd(){
	var obj1 = document.getElementById("id_onsite_shredding");
	var obj2 = document.getElementById("id_offsite_shredding");
	var obj3 = document.getElementById("id_drop_off_shredding");
	var obj4 = document.getElementById("id_recycling");
	
	if (!obj1 || !obj2 || !obj3 || !obj4)
		return false;
	
	addEvent(obj1, "click", checkReccyclingAlerd);
	addEvent(obj2, "click", checkReccyclingAlerd);
	addEvent(obj3, "click", checkReccyclingAlerd);
	addEvent(obj4, "click", checkReccyclingAlerd);
	//addEvent(zipField, "keypress", tryZipCode);
}

function checkReccyclingAlerd(){
	var obj1 = document.getElementById("id_onsite_shredding");
	var obj2 = document.getElementById("id_offsite_shredding");
	var obj3 = document.getElementById("id_drop_off_shredding");
	var obj4 = document.getElementById("id_recycling");
	
	var objAlert = document.getElementById("reccycling_alerd");
	
	if (!obj1 || !obj2 || !obj3 || !obj4 || !objAlert)
		return false;
	
	if((obj1.checked || obj2.checked || obj3.checked) && obj4.checked){
		objAlert.style.display = "block";
	} else {
		objAlert.style.display = "none";
	}
	
}


/* ----------------------------------------------------------------------
	ONGOING SERVICE stairs_involved
---------------------------------------------------------------------- */
function stairsInvolvedInit(){
	var stairsInvolvedYes = document.getElementById("id_stairs_involved_yes");
	var stairsInvolvedNo = document.getElementById("id_stairs_involved_no");
	
	if (!stairsInvolvedYes || !stairsInvolvedNo)
		return false;
	
	stairsInvolvedNo.checked = "checked";
	stairsInvolvedHidden();
	
	addEvent(stairsInvolvedYes, "click", stairsInvolvedShow);
	addEvent(stairsInvolvedNo, "click", stairsInvolvedHidden);
}

function stairsInvolvedShow(){
	stairsInvolvedDisplay("block");
}

function stairsInvolvedHidden(){
	stairsInvolvedDisplay("none");
}

function stairsInvolvedDisplay(dis){
	var sl1 = document.getElementById("how_many_stairs_line");
	var sl2 = document.getElementById("stair_type_line");
	
	if(!sl1 || !sl2)
		return;
	
	sl1.style.display = dis;
	sl2.style.display = dis;
	
}


/* ----------------------------------------------------------------------
	STRING
---------------------------------------------------------------------- */
function getRelativURL(url){
	var pos = lastIndex(url,"#");
	return url.substring(pos+1, url.length);
}

function lastIndex(txt, looking, startPos){
	if (startPos == undefined)
		startPos = 0;
	var pos = txt.indexOf(looking, startPos);
	if (pos < 0)
		return -1;
	
	var posNext = lastIndex(txt, looking, pos+1);
	return (posNext > pos)?(posNext):(pos);
}


/* ----------------------------------------------------------------------
	EQUIPMENT
---------------------------------------------------------------------- */
function eguipmentInit(){
	//Disabled All Input
	var allTags = document.getElementsByTagName("a");
	if (allTags) {
		for (q=0; q<allTags.length; q++) {
			obj = allTags[q];
			
			if (obj.className == "tolayer"){
				//obj.style.display = "none";
				//eguipmentShow();
				obj.onmouseover = function(){
					openMediaImage(getRelativURL(this.href), this.title);
				};
				
				obj.onmouseout = function(){
					BR_closeBrowser();
				};
				
				obj.onmousemove = BR_onmousemove;
			}
		}
	}
}

function getScrollY(){
	return parseInt( window.pageYOffset ? window.pageYOffset:
			(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) - 20 );
}

function eguipmentShow(eurl, etitle){
	//alert(eurl.title);
	openMediaImage(getRelativURL(eurl.href), eurl.title);
}


function openMediaImage(path, caption, type){
	var d = BR_CreateBrowser(caption);

	//Set image size
	var widthMax = 450;
	var heightMax = 550;
	
	//Content
	var mpContent = BR_CreateNewTag("div", "mpContent", "mediaContent");
	
	var a = BR_CreateNewTag("a", "mpA");
	var newAttr = document.createAttribute("href");
    newAttr.nodeValue = "#1";
    a.setAttributeNode(newAttr);
	
	var img = BR_CreateNewTag("img", "mpImg");
	newAttr = document.createAttribute("src");
    newAttr.nodeValue = "/converter?widthMax=" + widthMax + "&heightMax=" + heightMax + "&img=" + path;
    img.setAttributeNode(newAttr);
	a.appendChild(img);
	
	mpContent.appendChild(a);
	mpContent.style.display="none";
	d.appendChild(mpContent);
	
	//Preloader
	var preloader = BR_CreateNewTag("div", "mpPreloader");
	var swf = new FlashTag("/swf/circle.swf", 17, 17);
	preloader.innerHTML = swf.toString() + "<p>Loading Media...</p>";
	preloader.style.display="block";
	d.appendChild(preloader);	
	//BR_resize(d, 300);
	//BR_setPosition(d);
	
	if (img.complete)
		openMediaImageOnLoad();
	else
		addEvent(img, "load", openMediaImageOnLoad);
		
	addEvent(a, "click", BR_closeBrowser);
}

function openMediaImageOnLoad(){
	var mp = document.getElementById("mp");
	var mpPreloader = document.getElementById("mpPreloader");
	var mpContent = document.getElementById("mpContent");
	var mpImg = document.getElementById("mpImg");
	if (!mp || !mpPreloader || !mpContent)
		return;
	
	mpPreloader.style.display = "none";
	mpContent.style.display = "block";
	BR_resize(mp, mpImg.offsetHeight+27, mpImg.offsetWidth);
	//BR_setPosition(mp);
}


/* ----------------------------------------------------------------------
BROWSER ENGINE
---------------------------------------------------------------------- */
var BR_BrowserIsOpen = false;
var BR_BrowserObj = null;
var BR_Properties = new Object();

function BR_closeBrowser(){
	BR_BrowserIsOpen = false;
	BR_BrowserObj = null;
	
	var mp = document.getElementById("mp");
	if (!mp)
		return;
	mp.parentNode.removeChild(mp.parentNode.lastChild);
	
}

function BR_CreateBrowser(title){
	BR_closeBrowser();
	var d = BR_CreateNewTag("div", "mp");
	BR_addHeader(d, title);
	
	document.body.appendChild(d);
	BR_BrowserIsOpen = true;
	BR_BrowserObj = d;
	
	// Set window size
	BR_Properties.clientSize = getClientSize();
	BR_Properties.scrollXY = getScrollXY()
	return d;
}

function BR_resize(d, el_height, el_width){
	d.style.height = el_height + "px";
	d.style.width = el_width + "px";
}

function BR_setPosition(d){
	var scrolXY = getScrollXY();
	var size = getClientSize();
	var w = d.offsetWidth;
	//var sw = document.body.offsetWidth;
	d.style.left = ((size[0] - w) / 2) + "px";
	
	var h = d.offsetHeight;
	var sh = document.documentElement.clientHeight;
	//window.pageYOffset
	d.style.top = (((size[1] - h) / 2)+scrolXY[1]) + "px";
}

function BR_addHeader(d, tile){
	var mpHeader = BR_CreateNewTag("div", "mpHeader");
	mpHeader.innerHTML = "<h3 title=" + tile + ">" + tile + "</h3>";
	d.appendChild(mpHeader);
}

function BR_CreateNewTag(tagName, id, className){
	var tag = document.createElement(tagName);
	
	var newAttr;
	if (id != undefined){
		newAttr = document.createAttribute("id");
		newAttr.nodeValue = id;
		tag.setAttributeNode(newAttr);
	}
	if (className != undefined){
		newAttr = document.createAttribute("class");
		newAttr.nodeValue = className;
		tag.setAttributeNode(newAttr);
	}
	return tag;
}

function BR_addAttribute(element, attributeName, attributeValue){
	if (attributeName != undefined){
		var newAttr = document.createAttribute(attributeName);
		newAttr.nodeValue = attributeValue;
		element.setAttributeNode(newAttr);
	}
}

function BR_onmousemove(e){
	if (BR_BrowserObj == null)
		return;
	
	e = e || window.event;

	var mx, my;
	if (e.pageX) { 
		mx = e.pageX;
		my = e.pageY;

	} else if (e.clientX) {
		mx = e.clientX;
		my = e.clientY + getScrollY();
	}
	
	// Correct mx
	mx = mx + 20;
	mx = ((mx + BR_BrowserObj.offsetWidth) > BR_Properties.clientSize[0])?(mx - 30 - BR_BrowserObj.offsetWidth):(mx);
	
	// Corect my
	my = (((my + BR_BrowserObj.offsetHeight) - BR_Properties.scrollXY[1]) > BR_Properties.clientSize[1])?((BR_Properties.scrollXY[1] + BR_Properties.clientSize[1]) - BR_BrowserObj.offsetHeight):(my)
	
	BR_BrowserObj.style.left = mx + "px";
	BR_BrowserObj.style.top = my + "px";
	
	// document.title = BR_Properties.clientSize[0] + "px, " +
	// BR_Properties.clientSize[1] + "px | mx=" + mx + "px, my=" + my + "px |
	// scrollX=" +
	// BR_Properties.scrollXY[0] + "px, scrollY=" + BR_Properties.scrollXY[1] +
	// "px | objHeight=" +
	// BR_BrowserObj.offsetHeight + "px, objWidth=" + BR_BrowserObj.offsetWidth
	// + "px";
}

function getClientSize() {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  return [myWidth, myHeight]
	}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}


/* ----------------------------------------------------------------------
	SERVICES DESCRIPTION
---------------------------------------------------------------------- */
function initServicesDescription(){
	checkTagsSD(document.getElementsByTagName("input"));
	checkTagsSD(document.getElementsByTagName("label"));
}

function checkTagsSD(allTags){
	if (!allTags)
		return;
	
	for (q=0; q<allTags.length; q++) {
		obj = allTags[q];
		if (obj.className.indexOf("tolayer") > -1){
			addActionsSD(obj);
		}
	}
}

function addActionsSD(obj){
	var id = obj.id.substr(obj.id.length - 4, obj.id.length);
	
	obj.onmouseover = function(){
		openMediaSD(id);
	};
	
	obj.onmouseout = function(){
		BR_closeBrowser();
	};
	
	obj.onmousemove = BR_onmousemove;
}


function openMediaSD(objId){
	var labelSD = document.getElementById("service_type_label_" + objId);
	var descriptionSD = document.getElementById("service_description_" + objId);
	if (!labelSD || !descriptionSD)
		return;
	
	var d = BR_CreateBrowser(labelSD.innerHTML);

	//Set image size
	var widthMax = 450;
	var heightMax = 550;

	var mpContent = BR_CreateNewTag("div", "mpContent", "serviceContent");
	d.appendChild(mpContent);
	mpContent.innerHTML = descriptionSD.innerHTML;
	
	d.style.height = "auto";
	//alert("sdf");
		
}


/* ----------------------------------------------------------------------
	ADDRESS IS THE SAME
---------------------------------------------------------------------- */
function initTheSameAddress(){
	var ccBilling = document.getElementById("id_cc_billing");
	if (!ccBilling)
		return false;
	
	addEvent(ccBilling, "click", theSameAddressClick);
	theSameAddressClick();
}

function theSameAddressClick(){
	var ccBilling = document.getElementById("id_cc_billing");
	if (!ccBilling)
		return false;
	
	var fields = Array("contact_name", "phone", "email", "address", "address2", "city", "state", "zip");
	var check = ccBilling.checked;
	
	var q;
	for (q=0; q<fields.length; q++){
		theSameAddressChange(fields[q], check);
	}
}

function theSameAddressChange(fieldName, checkStatus){
	var objBillingName = "id_billing_" + fieldName;
	var objBilling = document.getElementById(objBillingName);
	if (!objBilling){
		alert("Field '" + objBilling + "' does not exist!");
		return;
	}
	
	var objServiceName = "id_service_" + fieldName;
	var objService = document.getElementById(objServiceName);
	if (!objService){
		alert("Field '" + objServiceName + "' does not exist!");
		return;
	}
	
	if (checkStatus){
		objBilling.value = objService.value;
		objBilling.className = "readonly";
		objBilling.readOnly = true;
	} else {
		objBilling.className = "";
		objBilling.readOnly = false;
	}
	
}

