var IsDirty=0;
var DidClick=0;
var useFlash=0;
var flashAppName="";

function HoverOut(){ 
	DidClick=0;
 }

function ShowMenu(MenuID){
	if (DidClick==1) {
		cswmShow(MenuID, MenuID, 'below');
	}
}

function ShowSideMenu(MenuID){
	cswmShow(MenuID, MenuID, 'right');
}

function ClickMenu(MenuID){
	DidClick=1;
	cswmShow(MenuID, MenuID, 'below');
}
function HideMenu(){
	cswmHide();
}


function SetDirty() {
	IsDirty=1;	
}

function OpenInOut(){
	// Figure out the window options
	var xpos = parseInt((screen.availWidth - 300));;
	var ypos = 0;
	var opt = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=290,height=500';
	var val, html, todo;

	// Center the window. One for NS one for IE
	opt += ',screenX='+xpos+',screenY='+ypos;
	opt += ',left='+xpos+',top='+ypos;

	var w = window.open('../admin/inout.aspx','InOut',opt);
	w.focus();
}

function OpenHelp(Page){
	OpenWindow(500, 500, 'http://app.crmgr.com/videos/default.htm');
}

function checkDirty(sURL) {
	if(String(flashAppName).length >=1){
		if (navigator.appName.indexOf("Microsoft")!= -1) {	
 			findSWF(flashAppName).checkFlashDirty = function(sVal) {
				string1 = "<invoke name=\"checkFlashDirty\" returntype=\"javascript\"><arguments><string>" + sVal + "</string></arguments></invoke>" ;
				Form1[flashAppName].CallFunction(string1);
			}
		}
		findSWF(flashAppName).checkFlashDirty(sURL);
	}else{
		if (IsDirty==1 && document.forms[0].noprompt==undefined){
			if (confirm("Do you want to save your changes ?"))
				{ document.forms[0].submit(); }
			else
				{ document.location.href=sURL; 
			}
		} else {
			document.location.href=sURL;
		}
	}

}

function findSWF(movieName) {
	if (navigator.appName.indexOf("Microsoft")!= -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function initFlashApp(controlName){

	flashAppName = controlName;
	if (navigator.appName.indexOf("Microsoft")!= -1) {
		window[flashAppName] = new Object();
		window[flashAppName].style = new Object();
		window[flashAppName].style.display = "";
	}

}
			
function Submit(Action){
	document.forms[0].PostAction.value=Action;
	document.forms[0].submit();
}


function SetPage(PagePosition){
	document.forms[0].PostAction.value='NewPage';
	document.forms[0].PagePosition.value=PagePosition;
	document.forms[0].submit();
}

function OpenWindow(wHeight, wWidth, sLink) {

	var xpos = parseInt((screen.availWidth - parseInt(wWidth))/2);
	var ypos = parseInt((screen.availHeight - parseInt(wHeight))/2);
	var opt = 'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width='+wWidth+',height='+wHeight;
	opt += ',screenX='+xpos+',screenY='+ypos+',left='+xpos+',top='+ypos;
	var w = window.open(sLink,"",opt);
	w.focus();
}

function setValue(target, val){
	var fld = eval("document.forms[0]."+target);
	fld.value=val;
}

function OpenWindow2(wHeight, wWidth, sLink) {

	var xpos = parseInt((screen.availWidth - parseInt(wWidth))/2);
	var ypos = parseInt((screen.availHeight - parseInt(wHeight))/2);
	var opt = 'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width='+wWidth+',height='+wHeight;
	opt += ',screenX='+xpos+',screenY='+ypos+',left='+xpos+',top='+ypos;
	var w = window.open(sLink,"xx",opt);
	w.focus();

}

function ShowActionLog(Entity, EntityKey){
	OpenWindow(400, 550, '../commonpages/log_detail.aspx?Entity='+Entity+'&EntityKey='+EntityKey);
}


function OpenReport(sLink) {

	var xpos = parseInt((screen.availWidth - parseInt(600))/2);
	var ypos = parseInt((screen.availHeight - parseInt(500))/2);
	var opt = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=600,height=500';
	opt += ',screenX='+xpos+',screenY='+ypos+',left='+xpos+',top='+ypos;
	var w = window.open(sLink,"",opt);
	w.focus();

}

function PNLookup() {
	OpenWindow(330, 800, '../lookup_project.aspx?PA=GO&PAF=PostAction&RC=PN&AO=3&Search='+escape(document.forms[0].PN.value))
}

function OpenFormWindow(FormKey) {
	OpenWindow(400, 525, '../forms/form.asp?FormKey='+FormKey);
}


function OpenReportWindow(sReport) {
	OpenWindow(450, 550, '../reports/report_exec.aspx?'+sReport);
}

function SetSort(fld) {
	if(document.forms[0]._sort.value==fld){
		document.forms[0]._sort.value=fld+' DESC';
	} else {
		document.forms[0]._sort.value=fld;
	}
	document.forms[0].PostAction.value='sort';
	document.forms[0].submit();
}

function ValidNumber(TestVar)
{
	
	var RetVal = 0;
	if ((TestVar!=null) && (TestVar!="")) {
		if (isNaN(TestVar)) {
			RetVal = 1;
		}
	}
	else
	{
		RetVal = 1;
	}
	
	return RetVal;
}

function ValidNumberGross(TestVar)
{
	
	var RetVal = 0;
	if ((TestVar!=null) && (TestVar!="")) {
		if (isNaN(TestVar)) {
			RetVal = 1;
		}

		if (TestVar < 0) {
			RetVal = 1;
		}
	}
	else
	{
		RetVal = 1;
	}
	
	return RetVal;
}

function FlipAll(lPosition){
	for(var i=0;i<document.Form1.length;i++){
		document.Form1[i].selectedIndex = lPosition;
	}
}

function SelectClick(){
	if (document.forms[0].GridCheck.checked){
		CheckAll('');
	} else {
		UnCheckAll('');
	}		
}
function GridCheck(TopName, Prefix){
	var chkbox=eval("document.Form1."+TopName);
	if(chkbox.checked){CheckAll(Prefix)}else{UnCheckAll(Prefix)}
}

function CheckAll(Prefix){
	if (Prefix=="" || Prefix==null){
		for(var i=0;i<document.Form1.length;i++){
			if(document.Form1[i].type=='checkbox'){
				document.Form1[i].checked = true;
			}
		}
	}else{
		var len = Prefix.length;
		for(var i=0;i<document.Form1.length;i++){
			var s = new String(document.Form1[i].name);
			if(document.Form1[i].type=='checkbox' && s.substring(0, len)==Prefix){
				document.Form1[i].checked = true;
			}
		}
	}
}

function UnCheckAll(Prefix){
	if (Prefix=="" || Prefix==null){
		for(var i=0;i<document.Form1.length;i++){
			if(document.Form1[i].type=='checkbox'){
				document.Form1[i].checked = false;
			}
		}
	}else{
		var len = Prefix.length;
		for(var i=0;i<document.Form1.length;i++){
			var s = new String(document.Form1[i].name);
			if(document.Form1[i].type=='checkbox' && s.substring(0, len)==Prefix){
				document.Form1[i].checked = false;
			}
		}
	}
}


function ShowHide(ObjectName){
	var obj = new getObj(ObjectName);
	obj.style.display = (obj.style.display == 'block') ? 'none' : 'block';
}

function getObj(name)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}

function ShowToolbar(){
	var open = new getObj('toolbar_open');
	var closed = new getObj('toolbar_closed');
	//var logo = new getObj('LogoHeader');
	
	open.style.display = 'block';
	//logo.style.display = 'block';
	closed.style.display = 'none';
	setCookie('sidebar', 'show');
	if(document.Form1.MonthCalendar != null) {
		MoveMDRight();
	}
}

function HideToolbar(){
	var open = new getObj('toolbar_open');
	//var logo = new getObj('LogoHeader');
	var closed = new getObj('toolbar_closed');
	open.style.display = 'none';
	//logo.style.display = 'none';
	closed.style.display = 'block';
	setCookie('sidebar', 'hide');
	if(document.Form1.MonthCalendar != null) {
		MoveMDLeft();
	}
}

function setCookie(name, value) { 
var exp = new Date(); 
exp.setTime(exp.getTime() + 1800000000000);
 
WriteCookie(name, value, exp, "/", false);

}

function WriteCookie(name, value, expires, path, domain, secure) { 
 var curCookie = name + "=" + escape(value) + 
    ((expires) ? "; expires=" + expires.toGMTString() : "") + 
    ((path) ? "; path=" + path : "") + 
    ((domain) ? "; domain=" + domain : "") + 
    ((secure) ? "; secure" : ""); 

 document.cookie = curCookie; 
 
}

String.prototype.trim = function() {
  return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");
}


/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function LTrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;


      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function Trim(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return RTrim(LTrim(str));
}






function add_item() {
    var source = document.forms[0].available;
    var dest = document.forms[0].selected;

    var h = ',';
    for (var i=0; i < dest.options.length; i++) {
        h += dest.options[i].value + ',';
    }

    var flag = 0;
    for (var i=0; i < source.options.length; i++) {
        if (source.options[i].selected && h.indexOf(','+source.options[i].value+',') == -1)
            dest.options[dest.length] = new Option(source.options[i].text,source.options[i].value);

        if (flag == 1 || source.options[i].selected) flag = 1;
    }

    if (flag == 0) alert('Please select an item to add');
    SetDirty();
}

function remove_item() {
    var dest = document.forms[0].selected;
    var flag = 0;
    for (var i=dest.options.length-1; i >=0;  i--) {
        if (dest.options[i].selected) {
            dest.options[i] = null;
            flag = 1;
        }
    }

    if (flag == 0) alert('Please select an item to remove');
    SetDirty();
}

function remove_all() {
    document.forms[0].selected.options.length = 0;
}

function add_all() {
    var source = document.forms[0].available;
    var dest = document.forms[0].selected;
    dest.options.length=0;
    for (var i=0; i < source.options.length; i++) {
        dest.options[i] = new Option(source.options[i].text,source.options[i].value);
    }
    SetDirty();
}

function load_values() {

    var source = document.forms[0].available;
    var dest = document.forms[0].selected;
    var req = document.forms[0].required;

    if (true) {
        if (dest.options.length == 0) {
            alert('You must select at least one item');
            return 0;
        }
    }

    if (req.value.length > 0) {
        var reqa = req.value.split(",");
        for (var i=0; i < source.options.length; i++) {
            for (var j=0; j < reqa.length; j++) {
                if (source.options[i].value == reqa[j]) {
                    var found = 0;
                    for (var k=0; k < dest.options.length; k++) {
                        if (reqa[j] == dest.options[k].value) {
                            found = 1;
                        }
                    }
                    if (found == 0) {
                        alert(source.options[i].text+" is a required field.");
                        return 0;
                    }
                }
            }
        }
    }

    var text = '';
    if (true) {

        if (0==0 || (source.options.length != dest.options.length) ||
           (0==0 && (source.options.length == dest.options.length))) {
            for (var i=0; i < dest.options.length; i++) {
                text += dest.options[i].value + ',';
            }
        }

    } else {

        var h = ',';
        for (var i=0; i < dest.options.length; i++) {
            h += dest.options[i].value + ',';
        }

        for (var i=0; i < source.options.length; i++) {
            if (h.indexOf(','+source.options[i].value+',') == -1)
                text += source.options[i].value + ',';
        }
    }

    // Trim off the last delimiter
    var pos = text.lastIndexOf(',');
    if (pos > -1) text = text.substr(0,pos);

    document.forms[0]._list.value = text;
    return 1;
}

function submit_form() {
    if (load_values()) document.forms[0].submit();
}

function dialog_form() {
    if (load_values()) {
        if (window.opener.save_picker(document.forms[0]._list.value,'')) {
            window.close();
        }
    }
}


function save_values() {
	if (document.forms[0].SelectedKeys != null) {
		var dest = document.forms[0].selected;
		var sKeys = "";
		var sNames = "";
		for (var i=0; i<=dest.options.length-1;  i++) {
			if (sKeys == "")
				{
				sKeys = dest.options[i].value;
				sNames = dest.options[i].text;
				}
			else
				{
				sKeys += '|'+dest.options[i].value;
				sNames += '|'+dest.options[i].text;
				}
		}

		document.forms[0].SelectedKeys.value = sKeys;
		document.forms[0].SelectedNames.value = sNames;
    }
}

function moveSelectedUp() {
    var flag = 0;
    var sel = document.forms[0].selected;
    for (var i=1; i < sel.options.length; i++) {
        if (sel.options[i].selected == true) {
            var t_value = sel.options[i].value;
            var t_text = sel.options[i].text;
            var t_selected = sel.options[i].selected;
            sel.options[i].value = sel.options[i-1].value;
            sel.options[i].text = sel.options[i-1].text;
            sel.options[i].selected = sel.options[i-1].selected;
            sel.options[i-1].value = t_value;
            sel.options[i-1].text = t_text;
            sel.options[i-1].selected = t_selected;
            flag = 1;
        }
    }
    if (flag == 0) alert('Please highlight a selected item to move it up');
}

function moveSelectedDown() {
    var flag = 0;
    var sel = document.forms[0].selected;
    for (var i=sel.options.length-2; i>=0; i--) {
        if (sel.options[i].selected == true) {
            var t_value = sel.options[i].value;
            var t_text = sel.options[i].text;
            var t_selected = sel.options[i].selected;
            sel.options[i].value = sel.options[i+1].value;
            sel.options[i].text = sel.options[i+1].text;
            sel.options[i].selected = sel.options[i+1].selected;
            sel.options[i+1].value = t_value;
            sel.options[i+1].text = t_text;
            sel.options[i+1].selected = t_selected;
            flag = 1;
        }
    }
    if (flag == 0) alert('Please highlight a selected item to move it down');
}

function URLEncode (str){

	var vendor = navigator["appName"];
	if (vendor!=null){
		vendor = vendor.toLowerCase();
		if(vendor=="microsoft internet explorer"){
			return URLEncode2(str)
		} else {
			return str;
		};
	} else {
		return str;
	}
	

}

function URLEncode2(str){
	if('a'.replace(/a/, function(){return '';}).length == 0){
        return str.replace(/[^a-z0-9]/gi, enc);
        function enc(cMatch){
            if(cMatch == ' ')return '+';
            var hex = cMatch.charCodeAt(0).toString(16);
            var len = hex.length;
            switch(len){
                case 0:
                    hex = '00';
                    break;
                case 1:
                    hex = '0'+hex;
                case 2:
                    break;
                defalt:
                    hex = hex.substring((len-2), len);
                    break;
            }
            return '%'+hex;
        }
	}else{
        var outSt = '';
        for(var c = 0;c < str.length;c++){
            var cCode = str.charCodeAt(c);
            if(((cCode > 47)&&(cCode < 58))||
               ((cCode > 64)&&(cCode < 91))||
               ((cCode > 96)&&(cCode < 123))){
                outSt += str.charAt(c);
            }else if(cCode == 32){
                outSt += '+';
            }else{
                var hex = cCode.toString(16);
                var len = hex.length;
                switch(len){
                    case 0:
                        hex = '00';
                        break;
                    case 1:
                        hex = '0'+hex;
                    case 2:
                        break;
                    defalt:
                        hex = hex.substring((len-2), len);
                        break;
                }
                outSt += '%'+hex;
            }
        }
        return outSt;
    }


}

function DD(DDPage, Source, ProjectKey, TaskKey) {
	var xpos = 100
	var ypos = 100
	var opt = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=800,height=550';

	// Center the window. One for NS one for IE
	//New Comment ****************************************************************************************************
	//New Comment ****************************************************************************************************
	//New Comment ****************************************************************************************************
	//New Comment ****************************************************************************************************
	opt += ',screenX='+xpos+',screenY='+ypos;
	opt += ',left='+xpos+',top='+ypos;
	
	//set parameter values
	var params='Source='+Source+'&ProjectKey='+ProjectKey+'&TaskKey='+TaskKey; //first parameter
	
	if (DDPage == 'labor')
		var w = window.open('../reports/dd_labor.aspx?'+params,"DD",opt);
	if (DDPage == 'expense')
		var w = window.open('../reports/dd_expense.aspx?'+params,"DD",opt);
	if (DDPage == 'po')
		var w = window.open('../reports/dd_po.aspx?'+params,"DD",opt);
	if (DDPage == 'invoice')
		var w = window.open('../reports/dd_invoice.aspx?'+params,"DD",opt);
	if (DDPage == 'advance_bill')
		var w = window.open('../reports/dd_invoice.aspx?AdvanceBill=1&'+params,"DD",opt);
	w.focus();
}
