// Copyright ? 2000 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.
//
// ************************
// layer utility routines *
// ************************

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
} // changeObjectVisibility

function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.left = newXCoordinate;
	styleObject.top = newYCoordinate;

	return true;
    } else {
	// we couldn't find the object, so we can't very well move it
	return false;
    }
} // moveObject


var xOffset=30;var yOffset=-5;
function showPopup(targetObjectId,eventObj, srcElementId, categoryDisplayType){
	if(eventObj){
		hideCurrentPopup();
		eventObj.cancelBubble=true;
		if(categoryDisplayType == 'horizontal'){
		    var relatedObject=document.getElementById(srcElementId);
			var newXCoordinate=YAHOO.util.Dom.getX(relatedObject);
			var newYCoordinate=YAHOO.util.Dom.getY(relatedObject)+30;
		}
		else{
			var relatedObject=YAHOO.util.Event.getRelatedTarget(eventObj);
            var newXCoordinate=YAHOO.util.Dom.getX(relatedObject)+80;
            var newYCoordinate=YAHOO.util.Dom.getY(relatedObject)-50;
		}
		YAHOO.log('newXCoordinate = '+newXCoordinate);
		YAHOO.log('newYCoordinate = '+newYCoordinate);
		YAHOO.util.Dom.setX(targetObjectId,newXCoordinate);
		YAHOO.util.Dom.setY(targetObjectId,newYCoordinate);
		if(changeObjectVisibility(targetObjectId,'hidden')){
			window.currentlyVisiblePopup=targetObjectId;
			return true;
		}
		else{
			return false;
		}
	}
	else{
		return false;
	}
}
//function showPopup(targetObjectId,eventObj){
//    if(eventObj){
//         hideCurrentPopup();
//         eventObj.cancelBubble=true;
//         var relatedObject=YAHOO.util.Event.getRelatedTarget(eventObj);
//         var newXCoordinate=YAHOO.util.Dom.getX(relatedObject)+80;
//         var newYCoordinate=YAHOO.util.Dom.getY(relatedObject)-50;
//         YAHOO.log('newXCoordinate = '+newXCoordinate);
//         YAHOO.log('newYCoordinate = '+newYCoordinate);
//         YAHOO.util.Dom.setX(targetObjectId,newXCoordinate);
//         YAHOO.util.Dom.setY(targetObjectId,newYCoordinate);
//         if(changeObjectVisibility(targetObjectId,'hidden')){
//             window.currentlyVisiblePopup=targetObjectId;
//               return true;
//         }
//         else{
//             return false;
//         }
//      }
//    else{
//       return false;
//    }
//  }

function hideCurrentPopup(){
	if(window.currentlyVisiblePopup){
		changeObjectVisibility(window.currentlyVisiblePopup,'hidden');
		window.currentlyVisiblePopup=false;
	}
}

window.onload=initializeHacks;document.onclick=hideCurrentPopup;function initializeHacks(){if((navigator.appVersion.indexOf('MSIE 5')!=-1)&&(navigator.platform.indexOf('Mac')!=-1)&&getStyleObject('blankDiv')){window.onresize=explorerMacResizeFix;}
resizeBlankDiv();createFakeEventObj();}
function createFakeEventObj(){if(!window.event){window.event=false;}}
function resizeBlankDiv(){if((navigator.appVersion.indexOf('MSIE 5')!=-1)&&(navigator.platform.indexOf('Mac')!=-1)&&getStyleObject('blankDiv')){getStyleObject('blankDiv').width=document.body.clientWidth-20;getStyleObject('blankDiv').height=document.body.clientHeight-20;}}
function explorerMacResizeFix(){location.reload(false);}

//global.js contents

/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
    obj.className = newStyle;
}

function isUndefined(value) {   
    var undef;   
    return value == undef; 
}

function checkAll(theForm) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
		var eName = e.name;
    	if (eName != 'allbox' && 
            (e.type.indexOf("checkbox") == 0)) {
        	e.checked = theForm.allbox.checked;		
		}
	} 
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
		if(element.type.indexOf("text") == 0 || 
				element.type.indexOf("password") == 0) {
					element.value="";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked=false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for(var j = 0; j < element.length ; j++) {
				element.options[j].selected=false;
			}
            element.options[0].selected=true;
		}
	} 
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
    var query = "";
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("checkbox") == 0 || 
            element.type.indexOf("radio") == 0) { 
            if (element.checked) {
                query += element.name + '=' + escape(element.value) + "&";
            }
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length ; j++) {
				if (element.options[j].selected) {
                    query += element.name + '=' + escape(element.value) + "&";
                }
			}
        } else {
            query += element.name + '=' 
                  + escape(element.value) + "&"; 
        }
    } 
    return query;
}

/* Function to hide form elements that show through
   the search form when it is visible */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden 
{
	for(var i = 0; i < frmObj.length; i++) {
		if (frmObj.elements[i].type.indexOf("select") == 0 || frmObj.elements[i].type.indexOf("checkbox") == 0) {
            frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
		}
	} 
}

/* Helper function for re-ordering options in a select */
function opt(txt,val,sel) {
    this.txt=txt;
    this.val=val;
    this.sel=sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list,to) {     
    var total=list.options.length;
    index = list.selectedIndex;
    if (index == -1) return false;
    if (to == +1 && index == total-1) return false;
    if (to == -1 && index == 0) return false;
    to = index+to;
    var opts = new Array();
    for (i=0; i<total; i++) {
        opts[i]=new opt(list.options[i].text,list.options[i].value,list.options[i].selected);
    }
    tempOpt = opts[to];
    opts[to] = opts[index];
    opts[index] = tempOpt
    list.options.length=0; // clear
    
    for (i=0;i<opts.length;i++) {
        list.options[i] = new Option(opts[i].txt,opts[i].val);
        list.options[i].selected = opts[i].sel;
    }
    
    list.focus();
} 

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/* This function is used to select a checkbox by passing
 * in the checkbox id
 */
function toggleChoice(elementId) {
    var element = document.getElementById(elementId);
    if (element.checked) {
        element.checked = false;
    } else {
        element.checked = true;
    }
}

/* This function is used to select a radio button by passing
 * in the radio button id and index you want to select
 */
function toggleRadio(elementId, index) {
    var element = document.getElementsByName(elementId)[index];
    element.checked = true;
}

/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
	winName = window.open(url, winTitle, winParams);
    winName.focus();
}


/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
    var screenWidth = parseInt(screen.availWidth);
    var screenHeight = parseInt(screen.availHeight);

    var winParams = "width=" + screenWidth + ",height=" + screenHeight;
        winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

    openWindow(url, winTitle, winParams);
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end) 
	return unescape(value);
}

/* This function is used to delete cookies */
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";
  }
}

// This function is for stripping leading and trailing spaces
function trim(str) { 
    if (str != null) {
        var i; 
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length); 
                break;
            } 
        } 
    
        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1); 
                break;
            } 
        } 
        
        if (str.charAt(0)==" ") {
            return ""; 
        } else {
            return str; 
        }
    }
} 

// This function is used by the login screen to validate user/pass
// are entered. 
function validateRequired(form) {                                    
    var bValid = true;
    var focusField = null;
    var i = 0;                                                                                          
    var fields = new Array();                                                                           
    oRequired = new required();                                                                         
                                                                                                        
    for (x in oRequired) {                                                                              
        if ((form[oRequired[x][0]].type == 'text' || form[oRequired[x][0]].type == 'textarea' || form[oRequired[x][0]].type == 'select-one' || form[oRequired[x][0]].type == 'radio' || form[oRequired[x][0]].type == 'password') && form[oRequired[x][0]].value == '') {
           if (i == 0)
              focusField = form[oRequired[x][0]]; 
              
           fields[i++] = oRequired[x][1];
            
           bValid = false;                                                                             
        }                                                                                               
    }                                                                                                   
                                                                                                       
    if (fields.length > 0) {
       focusField.focus();
       alert(fields.join('\n'));                                                                      
    }                                                                                                   
                                                                                                       
    return bValid;                                                                                      
}

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
    var e = document.createElement(element);
    e.setAttribute("name", name);
    e.setAttribute("type", type);
    e.setAttribute("id", id);
    e.setAttribute("value", value);
    parent.appendChild(e);
}

function confirmDelete(obj) {   
    var msg = "Are you sure you want to delete this " + obj + "?";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId); 
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows;
    if (tbody == null) {
        rows = table.getElementsByTagName("tr");
    } else {
        rows = tbody.getElementsByTagName("tr");
    }
    // add event handlers so rows light up and are clickable
    for (i=0; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[0];
            var link = cell.getElementsByTagName("a")[0];
            location.href = link.getAttribute("href");
            this.style.cursor="wait";
        }
    }
}

function highlightFormElements() {
    // add input box highlighting
    addFocusHandlers(document.getElementsByTagName("input"));
    addFocusHandlers(document.getElementsByTagName("textarea"));
}

function addFocusHandlers(elements) {
    for (i=0; i < elements.length; i++) {
        if (elements[i].type != "button" && elements[i].type != "submit" &&
            elements[i].type != "reset" && elements[i].type != "checkbox" && elements[i].type != "radio") {
            if (!elements[i].getAttribute('readonly') && !elements[i].getAttribute('disabled')) {
                elements[i].onfocus=function() {this.style.backgroundColor='#ffd';this.select()};
                elements[i].onmouseover=function() {this.style.backgroundColor='#ffd'};
                elements[i].onblur=function() {this.style.backgroundColor='';}
                elements[i].onmouseout=function() {this.style.backgroundColor='';}
            }
        }
    }
}

function radio(clicked){
    var form = clicked.form;
    var checkboxes = form.elements[clicked.name];
    if (!clicked.checked || !checkboxes.length) {
        clicked.parentNode.parentNode.className="";
        return false;
    }

    for (i=0; i<checkboxes.length; i++) {
        if (checkboxes[i] != clicked) {
            checkboxes[i].checked=false;
            checkboxes[i].parentNode.parentNode.className="";
        }
    }

    // highlight the row    
    clicked.parentNode.parentNode.className="over";
}

/**
 * This method checks whether the given image path format is correct or wrong.
 */
function isValidImagePath(imagePath){
  var validImage = true;
  var regex = /^[a-zA-Z]$/;
  var fileType = /^\.[a-zA-Z]{3,4}$/;
  var imagePathArray = imagePath.split(":");
  // to check whether the image path has drive name as well as the filename
  if(imagePathArray.length == 1){
    validImage = false;
  }
  //to check whether the image path has the valid drive name
  else if(imagePathArray.length > 1 && (imagePathArray[0].length > 1 || !regex.test(imagePathArray[0]))){
       validImage = false;
  }
  //to check whether the file name has the valid file extension.
  else if(imagePathArray.length > 1){
     var imagePathAfterColon = imagePathArray[imagePathArray.length-1];
     var fileExtension = imagePathAfterColon.substring(imagePathAfterColon.lastIndexOf("."),imagePathAfterColon.length);
     if(!fileType.test(fileExtension)){
      validImage = false;
     }
  }
 return validImage;
}

/**
 * The following method is for setting the maxlength attribute for the textarea.
*/
var W3CDOM = document.createElement && document.getElementsByTagName;
function setMaxLength() {
	if (!W3CDOM) return;
	var textareas = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'textblacknormal';
	for (var i=0;i<textareas.length;i++) {
		if (textareas[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.innerHTML = '<span>0</span>/'+textareas[i].getAttribute('maxlength');
			textareas[i].parentNode.insertBefore(counterClone,textareas[i].nextSibling);
			textareas[i].relatedElement = counterClone.getElementsByTagName('span')[0]; 
			textareas[i].onkeyup = textareas[i].onchange = checkMaxLength;
			textareas[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	//this is the temporary fix to solve the problem with the string length.
	if(maxLength > 400 && currentLength > (maxLength/2)){
	  currentLength = currentLength + 15;
	}
	if (currentLength > maxLength)
		this.relatedElement.className='text-red'
	else
		this.relatedElement.className='textblacknormal';
	this.relatedElement.firstChild.nodeValue = currentLength;
}

/**
 * Just a utility function for cleaning up the returned HTML response
 * and truncating it.
 */
var trunc = function(str, maxLen, maxWordLen) 
{
    // Strip markup
    str = str.replace("<b>", "");
    str = str.replace("</b>", "");
    str = str.replace("<B>", "");
    str = str.replace("</B>", "");
    
    // Simple truncation
    if(str.length > maxLen) {
        str = str.substring(0,maxLen) + "...";
    }

    // Truncate for long words
    var start = 0;
    var loopCnt = 0;
    var strSlice = str;
    
    do  {
        var spaceBreak = strSlice.indexOf(' ');
        var lenOfWord = spaceBreak;
        if(lenOfWord == -1)
        {
            lenOfWord = strSlice.length;
        }

        if (lenOfWord > maxWordLen) {
            //debugMsg("Long word found in: " + strSlice);
            str = str.substring(0, maxWordLen);  // TRUNCATE
        }
        start = spaceBreak+1;
        strSlice = strSlice.substring(start);
        spaceBreak = strSlice.indexOf(' ');
    } while(spaceBreak != -1)
    
    return str;
};

// Show the document's title on the status bar
window.defaultStatus=document.title;

