/*
 * JavaScript Functions for Web Application Client ( app.js)
 *
 * (c) Copyright Zaidsoft. All Rights Reserved.
 * 
 * This software is the proprietary information of Zaidsoft. 
 * 
 * No part of this software can be reused without explicit written 
 * permission of  Zaidsoft. (www.zaidsoft.com)
 *
 * All Use(s) is(are) subject to license terms.
 * 
 */

//////////////////////////////////////////////////////////////////
/// Show a loading box while the page is being loaded
///////////////////////////////////////////////////////////////////

var showLoadingBox = false;



if (showLoadingBox){
    // set a method for onload so the loading box can be hidden after loading
    addLoadEvent(function() {
      // more code to run on page load 
      document.getElementById('loadingBox').style.visibility='hidden';
      document.body.style.cursor = nfOldCursor;
    });
    // output a loading box 
    document.write("<div id='loadingBox' class='pageCenteredSmall' align='center'><br><br>Loading. Please wait...</div>");
    var nfOldCursor = document.body.style.cursor;
    document.body.style.cursor='wait';
}
// -----------------------------------------------------------------
	

msg = "Why bother with Right Click. \nYou can do everything with just a few Left Clicks";
function Protect(b) {
	   if(((navigator.appName=="Microsoft Internet Explorer")&&(event.button > 1))
	   ||((navigator.appName=="Netscape")&&(b.which > 1))){
	   alert(msg);
	   return false;
	   }
}
//document.onmousedown = Protect;




// ------------------------------------------------
// Display an hour-glass (wait symbol) whenever a form
// is submitted and display text "Please wait..."
// as button caption so the user may know that some processing 
// is underway resulting in better user interface. It also provides
// immunity from double submitting the data/form
// Tested with: I.E./Mozilla/Opera (latest)
// -----------------------------------------------------
//window.document.onclick=myonclick;// disable for now
var formAlreadySubmitted = false;
var formSubmitButton = null;
function myonclick(event){
	if ( document.all ){
		var btn = self.event.srcElement;
	}
	else {
		var btn = event.target;
	}
	if (btn.type == 'submit'){
	   	formSumbitButton = btn;
		var myfrm = btn.parentElement;
		var cVar = myfrm.onsubmit();
		self.event.cancelBubble=true;
		alert (cVar);
		if(cVar) {
			// show wait cursor
			document.body.style.cursor='wait';
			// disable the form submit button	
			btn.value='Please wait...';
					
			myfrm.onsubmit = "";
			btn.disabled=true;
		 	myfrm.submit();
		}
		return false;
		
		// This is form submission so do some 
		// usefull things here
		// alert (btn + "  " + btn.parentElement);
		// sqlEscape(btn.parentElement);
		// document.body.style.background='silver';
		// I.E. will not submit the form if the submit button
		// is disabled so we need another trick here
		if ( document.all){
			if ( formAlreadySubmitted == true){
				// dont let the event bubble up
				self.event.cancelBubble=true;
				//alert ("Cancelled bubbling");
				return false;
			}
		}
		else {
			// for Mizilla disable the button simply
			//alert("going to disable the button");
			btn.disabled=true;
		}
		formAlreadySubmitted = true;
	}
}

// ------------------------------------------------------ //

//////////////////////////////////////////
// Make the input (text) field values of a form
// SQL compliant.
// i.e., Replace any single (') with ('' ) char
///////////////////////////////////////////////
function sqlEscape(frm){
	var ipts = frm.elements.tags('INPUT');
	for (i=0; i < ipts.length; i++){
		var vlu = ipts[i].value;
		// It may be that string alreay has double of these
		// TODO: try to find elagent solution later
		vlu = vlu.replace("''", "'");
		vlu = vlu.replace("''", "'");
		vlu = vlu.replace("''", "'");
		if ( vlu.indexOf("'") != -1){
			frm.elements.tags('INPUT')[i].value = vlu.replace("'", "''");
		}
	}
}
 
function round4Money(amount){
	if (amount.toFixed) {//if browser supports toFixed() method
		return amount.toFixed(2)
	}
	else{
		return Math.round(amount*1000)/1000;
	}
}

// this funtion protects double submitting of the html form
// call this at the end of the validate method for the form

// Creating problems when more than on sumbit button is there
// TODO: Fix this.

function protectDoubleSubmit(givenFrm){
	var sButton = null;
        var sButtonCount = 0;
	//var ipts = givenFrm.elements.tags('INPUT');
        var ipts = givenFrm.getElementsByTagName("INPUT");
	for (i=0; i < ipts.length; i++){
		var type = ipts[i].getAttribute("type");
		if ( type == "submit"){
			sButton = ipts[i]; 
                        sButtonCount ++;
		}
	}
        // if sButton is null then it may be possible that <button tag is being used
        if (sButton == null){
            ipts = givenFrm.getElementsByTagName('BUTTON');
            for (i=0; i < ipts.length; i++){
		var type = ipts[i].getAttribute("type");
		if ( type == "submit"){
			sButton = ipts[i];
                        sButtonCount ++;
		}
            }
        }

        // when using this with more than one sumbit button is causing issues
        // so for now we are using the disbale functions for 1 button case only
        if (sButtonCount == 1){  
            //sButton.value='Please wait...'; 
            //document.body.style.cursor='wait';
            //sButton.disabled='true';
        }
}




// this funtion protects double submitting of the html form
// call this at the end of the validate method for the form

// Creating problems when more than on sumbit button is there
// TODO: Fix this.

function protectDoubleSubmit_REM_WORING_IN_IE_ONLY(givenFrm){
	var sButton = null;
        var sButtonCount = 0;
	//var ipts = givenFrm.elements.tags('INPUT');
        var ipts = givenFrm.getElementsByTagName("INPUT");
	for (i=0; i < ipts.length; i++){
		var type = ipts[i].type;
		if ( type == "submit"){
			sButton = ipts[i]; 
                        sButtonCount ++;
		}
	}
        // if sButton is null then it may be possible that <button tag is being used
        if (sButton == null){
            ipts = givenFrm.elements.tags('BUTTON');
            for (i=0; i < ipts.length; i++){
		var type = ipts[i].type;
		if ( type == "submit"){
			sButton = ipts[i];
                        sButtonCount ++;
		}
            }
        }

        // when using this with more than one sumbit button is causing issues
        // so for now we are using the disbale functions for 1 button case only
        if (sButtonCount == 1){    
            //sButton.value='Please wait...'; 
            //document.body.style.cursor='wait'; 
            //sButton.disabled='true';
            //givenFrm.submit();
        }
}



function trimString (str) {
  //str = this != window? this : str;
  if (str == null) return str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

/* Appends another onLoad() event handler
   to existing hadlers.
   Previously added handlers will be executed first
   Taken from: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
   To use you can write an inline funtion in script tag alos like:
        addLoadEvent(function() {
            // more code to run on page load
        });
*/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}


// Cookie functions
// we assume that the normal use of cookie is to store a permanent cookie
// with a name and value
// the path is assumed to be the whole server (domain)
/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// generic setCookie Function
function setCookieGeneric(name, value, expires, path, domain){ 
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null)    ? "" : "; path=" + path) +
  ((domain == null)  ? "" : "; domain=" + domain);
}

// generic setCookie Function
function setCookie(name, value){ 
  var now = new Date()
	fixDate(now);
	now.setTime(eval(now.getTime() + (365 * 24 * 60 * 60 * 1000)));
//	now.setTime(now.getTime());
	setCookieGeneric(name, value, now, "/", null);
}

// date - any instance of the Date object
// * you should hand all instances of the Date object to this function for "repairs"
// * this function is taken from Chapter 14, "Time and Date in JavaScript", in "Learn Advanced JavaScript Programming"
function fixDate(date) {
        var base = new Date(0);
        var skew = base.getTime();
        if (skew > 0)
                date.setTime(date.getTime() - skew);
}

var oldCursor;
function showLoadingBox(){
	oldCursor = document.body.style.cursor;
	addLoadEvent(function() {
		  // more code to run on page load 
		  document.getElementById('loadingBox').style.visibility='hidden';
		  document.body.style.cursor = oldCursor;
	});
	document.write("<div id='loadingBox' class='pageCentered' align='center'><br><br>Loading. Please wait...</div>");
	document.body.style.cursor='wait';
}


function injectJS (fileName, jsbase){
	var src = jsbase + '/' + fileName + '.js';
	var ipts = document.getElementsByTagName("script");
    var found = false;
	for (i=0; i < ipts.length; i++){
		var type = ipts[i].src;
		if (type.indexOf(fileName) != -1){
                    found = true;
		}
      }
     if (!found){
	var headID = document.getElementsByTagName("head")[0];         
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = src;
	headID.appendChild(newScript);			
    }
 }	
 
 
 function injectCSS (fileName, cssbase){
	var ipts = document.getElementsByTagName("link");
    var found = false;
	for (i=0; i < ipts.length; i++){
		if ( ipts[i].rel != 'stylesheet') continue;
		var type = ipts[i].href;
		if (type.indexOf(fileName) != -1){
                    found = true;
		}
      }
     if (!found){
		var headID = document.getElementsByTagName("head")[0];         
        var c = document.createElement('link');
        c.type = 'text/css';
        c.rel = 'stylesheet';
        c.href = cssbase + '/' + fileName + '.css';
        headID.appendChild(c);			
    }
 }	



