/* util.js
    Created by Alex Brelsfoard
    This is a collection of useful javascript functions 
    to be used by the admin interface on the air2water 
    websites.
======================================================= */
var UTIL = {

	GetElement : function(elem) {
		var elem_id = elem;
		var return_elem;
		if( document.getElementById ) {// this is the way the standards work
			return_elem = document.getElementById( elem_id );
		}else if( document.all ) {// this is the way old msie versions work
			return_elem = document.all[elem_id];
		}else if( document.layers ) {// this is the way nn4 works
			return_elem = document.layers[elem_id];
		}
		return return_elem;
	},
    
    FindDealers : function() {
        var zip = UTIL.GetElement('zipcode').value;
        if (zip) {
            UTIL.GetElement('local_dealers').innerHTML = '<img src="/images/loaders/loader_6.gif" alt="loading" />';
            var ajaxRequest = AJAX.MakeRequest("/cgi-bin/dealers.cgi?zip="+zip, 'GET');
            ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                    var content = ajaxRequest.responseText;
                    if (content) {
                        UTIL.GetElement('local_dealers').innerHTML = content;
                    }else {
                        UTIL.GetElement('local_dealers').innerHTML = '<p>No dealers found in your area. Sorry.  Please check back soon.</p>';
                    }
                }
            }
        }
    },
	
	Hide : function(elem) {
		var this_elem = elem;
		UTIL.GetElement(this_elem).style.display = 'none';
	},
	
	Show : function(elem) {
		var this_elem = elem;
		UTIL.GetElement(this_elem).style.display = 'block';
	},
	
	ShowTBody : function(elem) {
		var this_elem = elem;
		UTIL.GetElement(this_elem).style.display = 'table-row-group';
	},

	ToggleDisplay : function(elem) {
        var this_elem = UTIL.GetElement(elem);
        if (this_elem.style.display == 'none' || this_elem.style.display == '') {
           UTIL.Show(elem);
        }else {
           UTIL.Hide(elem);
        }
	},
	
	Go : function(loc) {
		document.location = loc;
	},
	
	SelectAll : function(elem_id) {
		var elem = UTIL.GetElement(elem_id);
		for(i=0; i<elem.options.length; i++) {
			elem.options[i].selected = true;
		}
	},
	
	UnselectAll : function(elem_id) {
		var elem = UTIL.GetElement(elem_id);
		for(i=0; i<elem.options.length; i++) {
			elem.options[i].selected = false;
		}
	},
	
	ToggleCheckboxes : function(elem_id,wantsChecked) {
		var inputs = UTIL.GetElement(elem_id).getElementsByTagName('input');
		for(i=0; i<inputs.length; i++) {
			if (inputs[i].type == 'checkbox') {
			    inputs[i].checked = wantsChecked;
			}
		}
	},

	CreateCookie : function(name,value,days) {
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = "; expires="+date.toGMTString();
		}
		document.cookie = name+"="+escape(value)+expires+"; path=/";
	},

	ReadCookie : function(name) {
		var cookie_value ='';
		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) {
				cookie_value = c.substring(nameEQ.length,c.length);
			}
		}
		return cookie_value;
	},

	DeleteCookie : function(name) {
		UTIL.CreateCookie(name,"",-1);
	},
	
	ScrollToBottom : function (elem) {
		elem = UTIL.GetElement(elem);
		elem.scrollTop = elem.scrollHeight;
	},
	
	GetNumRows : function(txt_box, num_cols) {
        var val = txt_box.value;
//        var num_cols = txt_box.cols;
        var txt_length = val.length;
        var num_rows = 1;
        
        for (i=0;i<txt_length;i++) {
            if (val.charAt(i).charCodeAt(0) == 13) {
                num_rows +=1;
            }
        }
        
        if (num_rows < (txt_length / num_cols)) {
            num_rows = 1 + (txt_length / num_cols);
        }
        return num_rows;
	},
	
    UpdateTextBoxSize : function(id) {
        var text_box = UTIL.GetElement(id);
        var num_rows = UTIL.GetNumRows(text_box,42);
        if (num_rows > 3) {
            text_box.rows = num_rows;
        }
	},
	
	GetWindowDims : function() {
		var dims = [];
		if (document.all) {
				dims[0] = document.body.offsetWidth;
				dims[1] = document.body.offsetHeight;
		} else {
				dims[0] = window.innerWidth;
				dims[1] = window.innerHeight;
		}

// 		if (parseInt(navigator.appVersion)>3) {
// 			if (navigator.appName=="Netscape") {
// 				dims[0] = window.innerWidth;
// 				dims[1] = window.innerHeight;
// 			}
// 			if (navigator.appName.indexOf("Microsoft")!=-1) {
// 				dims[0] = document.body.offsetWidth;
// 				dims[1] = document.body.offsetHeight;
// 			}
// 		}
		return dims;
	},
	
	GetZIndex : function(id){
		var obj = UTIL.GetElement(id);
		var zIndex = 0;
		if (obj.currentStyle) {
			zIndex = parseFloat(obj.currentStyle['zIndex']);  
		} else if (window.getComputedStyle) {
			zIndex = parseFloat(document.defaultView.getComputedStyle(obj,null).getPropertyValue('z-index'));  
		}
		// Return the found zIndex only if it's a real value
		if( ! isNaN(zIndex) ) {
			return zIndex;
		}
		// otherwise return 0
		return 0;
	},
	
	CreateOverlay : function(type, content, x, y) {
		var overlay;
		var window_dims = UTIL.GetWindowDims();
		var curWinWidth = window_dims[0];
		var curWinHeight = window_dims[1];
		if (x === undefined) {
			var o_width = 200;
			if (type == 'sm') {
				o_width = 200;
			}else if (type == 'lg') {
				o_width = 650;
			}
			if (curWinWidth > o_width) {
				x = (curWinWidth - o_width) / 2;
			}else {
				x=0;
			}
			y=50;
		}
		
		var scroll_diff = (document.all) ? document.body.scrollTop : window.pageYOffset;
		y = (scroll_diff) ? y + scroll_diff : y;
		
		var window_dims = UTIL.GetWindowDims();
		var win_width = window_dims[0];
		var win_height = window_dims[1];
		// Get the size of the page, by getting the position of the footer div.
		var footer_top = UTIL.GetElement('footer').offsetTop + 20;
		footer_top = (footer_top < win_height) ? win_height : footer_top;
		
		var menu_cont = UTIL.GetElement('index_content');
		var overlay_name  = 'overlay_'+type;
		var overlay_menu_name  = 'overlay_'+type+'_menu';
		var overlay_top_name  = 'overlay_'+type+'_top';
		var overlay_content_name  = 'overlay_'+type+'_content';
		var overlay_bottom_name  = 'overlay_'+type+'_bottom';
		
		// Create the new overlay container window
		var overlay_cont = document.createElement('div');
		overlay_cont.setAttribute('id','overlay_background');
		overlay_cont.setAttribute('class','overlay_background');
		overlay_cont.style.className ='overlay_background';	// For IE
		overlay_cont.style.height = footer_top+'px';
		overlay_cont.id='overlay_background';		// for IE
		overlay_cont.innerHTML = '<img src="/images/clear.gif" width="'+curWinWidth+'" />';		// for IE
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			overlay_cont.style.backgroundImage = "url(/images/white_faded.gif)";
		}
		
		// Create the container for the new overlay div
		var overlay = document.createElement('div');
		overlay.setAttribute('id','overlay');
		overlay.setAttribute('class',overlay_name);
		overlay.style.className =overlay_name;	// For IE
		overlay.id='overlay';
		
		// Create the new overlay menu div
		var overlay_menu = document.createElement('div');
		overlay_menu.setAttribute('id','overlay_menu');
		overlay_menu.setAttribute('class',overlay_menu_name);
		overlay_menu.style.className =overlay_menu_name;	// For IE
		overlay_menu.id='overlay_menu';		// for IE
		
		// Create the new overlay content window
		var overlay_data = document.createElement('div');
		overlay_data.setAttribute('id','overlay_content');
		overlay_data.setAttribute('class',overlay_content_name);
		overlay_data.style.className =overlay_content_name;	// For IE
		overlay_data.id='overlay_content';		// for IE
		
		// Create the bottom of the overlay content window
/*
		var overlay_top = document.createElement('div');
		overlay_top.setAttribute('id','overlay_top');
		overlay_top.setAttribute('class',overlay_top_name);
		overlay_top.style.className =overlay_top_name;	// For IE
		overlay_top.id='overlay_top';		// for IE
		overlay_top.innerHTML = '&nbsp;';
*/
		
		// Create the bottom of the overlay content window
		var overlay_bottom = document.createElement('div');
		overlay_bottom.setAttribute('id','overlay_bottom');
		overlay_bottom.setAttribute('class',overlay_bottom_name);
		overlay_bottom.style.className =overlay_bottom_name;	// For IE
		overlay_bottom.id='overlay_bottom';		// for IE
		overlay_bottom.innerHTML = '&nbsp;';
		
		// Add the overlay container to the web page.
		menu_cont.appendChild(overlay_cont);
		// have to add this next line in there for IE to recognize the CSS class.
		UTIL.GetElement('overlay_background').className = 'overlay_background';
		
		// Add the overlay container to the web page.
		overlay_cont.appendChild(overlay);
		// have to add this next line in there for IE to recognize the CSS class.
		UTIL.GetElement('overlay').className = overlay_name;
		
		// Add the overlay menu div to the web page.
		overlay.appendChild(overlay_menu);
		// have to add this next line in there for IE to recognize the CSS class.
		UTIL.GetElement('overlay_menu').className = overlay_menu_name;
		var menu_content = "<div id=\"overlay_menu\" class=\"overlay_menu\"><div class=\"menu_close_left\" onClick=\"UTIL.CloseWindow();\">Close</div><div class=\"menu_close_right\" onClick=\"UTIL.CloseWindow();\">Close</div><span id=\"menu_title\">Menu</span><div class=\"clear\"></div></div>";
		overlay_menu.innerHTML = menu_content;
		
		// Add the overlay content window to the web page.
//		overlay.appendChild(overlay_top);
		overlay.appendChild(overlay_data);
		overlay.appendChild(overlay_bottom);
		// have to add this next line in there for IE to recognize the CSS class.
//		UTIL.GetElement('overlay_top').className = overlay_top_name;
		UTIL.GetElement('overlay_content').className = overlay_content_name;
		UTIL.GetElement('overlay_bottom').className = overlay_bottom_name;
		// Populate the overlay
		overlay_data.innerHTML = content;
		// position the overlay
		overlay.style.top =y+'px';
		overlay.style.left=x+'px';
		// Make clicking outside the popup window close it
	//	overlay_cont.setAttribute('onClick','MASTER.CloseWindow()');
//	    overlay_cont.onclick = function() {MASTER.CloseWindow();};
		// Show the overlay
		overlay_cont.style.visibility = "visible";
		
		return overlay_data;
	},
    
    CloseWindow : function() {
        UTIL.RemoveOverlay();
//        MASTER.overlay_is_open = false;
    },
	
	RemoveOverlay : function() {		
//		UTIL.GetElement('overlay_container').removeChild(UTIL.GetElement('overlay_content'));
		if (UTIL.GetElement('overlay_background')) {
			UTIL.GetElement('index_content').removeChild(UTIL.GetElement('overlay_background'));
		}
	},
	
	CheckForm : function(theForm) {
		UTIL.Hide('captcha_error');
		// Check that a message exists.
		if (!UTIL.GetElement(theForm).message.value) {
			alert("Don't you have anything to say?");
		// Check that a name exists
		}else if (!UTIL.GetElement(theForm).sender_name.value) {
			alert("Don't be shy.  Tell us your name.  At least give us A name.");
		// Check that the captcha is good.
		}else {
			var c = UTIL.GetElement('c').value;
			var guess = UTIL.GetElement('c_guess').value;
			var ajaxRequest = AJAX.MakeRequest("/cgi-bin/cap.pl?c="+c+"&guess="+guess, 'GET');
			// Function that will receive data sent from the server
			ajaxRequest.onreadystatechange = function(){
				if(ajaxRequest.readyState == 4){
					var success = parseInt(ajaxRequest.responseText);
					if (success) {
						UTIL.GetElement(theForm).submit();
					}else {
						CAP.ChangeCaptcha();
						UTIL.GetElement('captcha_error').innerHTML='Invalid Captcha entry.  Please try again.';
						UTIL.Show('captcha_error');
						UTIL.GetElement('c_guess').focus();
						alert("Invalid Captcha entry.  Please try again.");
					}
				}
			}
		}
	},
	
	ClearNLName : function(field) {
		if (field.value == 'Your Name') {
			field.value = '';
			field.className = 'newsletter_new';
		}
	},
	
	ResetNLName : function(field) {
		if (field.value == '') {
			field.className = 'newsletter';
			field.value = 'Your Name';
		}
	},
	
	ClearNLEmail : function(field) {
		if (field.value == 'Your Email Address') {
			field.value = '';
			field.className = 'newsletter_new';
		}
	},
	
	ResetNLEmail : function(field) {
		if (field.value == '') {
			field.className = 'newsletter';
			field.value = 'Your Email Address';
		}
	},
	
	AddToNewsletter : function() {
		var email = UTIL.GetElement('nl_email').value;
		if (email != 'Your Email Address' && email != '' &&email.indexOf('@') > 0) {
			var name = UTIL.GetElement('nl_name').value;
			var country = UTIL.GetElement('nl_country')[UTIL.GetElement('nl_country').selectedIndex].value;
			var ajaxRequest = AJAX.MakeRequest("/?a=nl&e="+email+"&c="+country+"&n="+name, 'GET');
			// Function that will receive data sent from the server
			ajaxRequest.onreadystatechange = function(){
				if(ajaxRequest.readyState == 4){
					var msg = ajaxRequest.responseText;
					if (msg) {
						alert(msg);
						UTIL.GetElement('nl_name').value = 'Your Name';
						UTIL.GetElement('nl_email').value = 'Your Email Address';
					}
				}
			}
		}else{
		  alert('Please enter a valid email address.');
		}
	},
	
	NewWinWithURL : function(url) {
		var win = window.open("http://"+url, '','');
	}
}

1;


