/*====================================================================================================
Global Javascript - used by the majority of forms in the application
====================================================================================================*/
window.onbeforeunload = checkWindowUnload;
var isDirty = false;
var currentView;
var ctrlFlg=false;
var ctrlFlgIE=true;
var altFlg=false;
var yesToStartEdit; 
var msgDisplay=0;


//Interaction Web Control
function showInteractDetails(f) {
	var el = document.getElementById('Interact_panDetails');
	if (el) {
		if (f == 1) {
			el.style.display = 'block';
		} else {
			el.style.display = 'none';
	}
	}
}

function navFocus() {
	var el = document.getElementById('lstView');
	if (arguments.length > 0) {
		if (arguments[0] != '') {
			el.value = arguments[0];
			currentView = arguments[0];
		}
	}

	if (el) {
		el.focus();
	}
	
}
function chkEmailID(obj)
{
		if (obj.value!='' )
		{
			var validEmailId = false;
			var sEmail = obj.value;
			if (sEmail.indexOf('@') > 0)
			{	
				var arrA = sEmail.split("@");
				if (arrA.length == 2)   // means Email have only one @ 
				{	var indexofDot = arrA[1].indexOf('.');
					if(indexofDot <= 0)
					{	validEmailId = false
					}
					else
					{	validEmailId = true
					}
				}
				else
				{	validEmailId = false
				}
			}
			if(!validEmailId)
			{
				alert('Please Insert Valid Email Id');
				obj.focus();
				return validEmailId;
			}
		}
}
function chkValid(fOK)
{
	var i;
	
	for (i=0; i<document.all.length; i++)
		{
			iReq = document.all(i).required;
			iChkEmail = document.all(i).chkEmail;	
			
			if(iChkEmail == "1")
			{
				var isValidEmail = chkEmailID(document.all(i));
				if(isValidEmail == false)
				{return false;}
				
			}
			switch(iReq)
			{
				case "1":
					if (document.all(i).type == "select-one")
					{ 
						if(document.all(i).value == '' || document.all(i)[document.all(i).selectedIndex].text == "Select One")
						{
							var sMsg = document.all(i).invalidMsg;
							alert (sMsg);
							fOK=false;
							document.all(i).focus();
							break;
						}
					}
					else if (document.all(i).value == '')
					{
						var sMsg = document.all(i).invalidMsg;
						alert (sMsg);
						fOK=false;
						document.all(i).focus();
						break;
					}
			}
			if (!fOK){break;}
		}

			return fOK;
			
}
function doCommand(s) {

	var el = document.getElementById('txtCommand');
	var f = document.getElementById('form1');
	var isSave = false;
	var isDelete = false;
	var fOK = true;
	//determine if 'save' is a part of the command...  if so, ignore isDirty variable	
	if (s.split('save').length > 1) {isSave = true}
	if (s.split('delete').length > 1) {isDelete = true}
	
	if (s == 'undo') {isDirty = false;}
	
	if (s == 'View' | s == 'view') {		
		var tab = arguments[1];		
		if ((tab.toString()).length > 0) {			
			if (tab < 10000) {
				changeView(tab,1); 
				fOK = false;
			} else {
				fOK = false;
			}
		}
	}
	
	if (isDelete) {
		fOK = window.confirm('Are you sure you wish to delete this record?');
	}
	
	if (isSave) {
		if (self.doValidate) {
			fOK = doValidate();
		} else { 
			fOK = true;
		}
		if (fOK) { isDirty = false }
		
		
		fOK = chkValid(fOK);

		
	}
		
	if (fOK) {
		if (arguments.length > 1) {
			for (var a=1; a < arguments.length; a++) {
				s = s + ',' + arguments[a];
			}
		}
		el.value = s;
		f.submit();
	}
	
}

//Function for changing bgColor of TextBox, DropDownBox, TextArea etc.
//-------------------------------------------------------------------

function startEdit(e,a) {

	var key;			
	flg=false;	
	
	// If condition for changing color of dropdown list in FireFox browser
	
	if(navigator.userAgent.indexOf("Mozilla/5")!=-1)
	{
		a.style.backgroundColor = "yellow";
		isDirty = true;
	}else
	{
	}
	
	if(window.event) 
	{			
		//alert("IE");	
		key=event.keyCode;		
		ctrlFlg=false;			
		altFlg=false;
		
		if(key==7 || key==10 || key==11 || key==13 || key==17 || key==20 || key==21)
		{
			ctrlFlg=true;
		}			
	}
	else if(e.which) 
	{
		// netscape		
		key = e.which; 		
		ctrlFlg = e.ctrlKey;	
		altFlg = e.altKey;
		
		if(ctrlFlg==true && (key==118 || key==86) || (key==120 || key==88))
		{
			ctrlFlg = false;
			//alert(ctrlFlg);
		}		
	}
	else {
		// no event, so pass through
		return true;
	}
	
		
	if(altFlg==false && ctrlFlg==false)
	{		
		a.style.backgroundColor = "yellow";	
		isDirty = true;	
	}else
	{
		
	}
	

}



function KeyCheck(e)
{

	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	
	
	var el = event.srcElement;
	
	if (el.onkeypress) {
		var sFunc = el.onkeypress.toString();
		var i = sFunc.indexOf('startEdit');
		
		if (i != -1) {
			//alert('Editable');
			yesToStartEdit=true;
		} else {
			alert('Not Editable');			
		}
	} else {
		//alert('Not Editable outer');
		yesToStartEdit=false;
	}

	
	if(window.event.ctrlKey)
	{
		ctrlFlgIE=true;
	}else if(window.event.altKey)
	{
		altFlg=true;	
	}
	else
	{
		ctrlFlgIE=false;
		altFlg=false;
	}
	
	key=KeyID;
    
	if(ctrlFlgIE==true && ((key==118 || key==86) || (key==120 || key==88)))
	{
		//alert("x or v");		
		ctrlFlgIE = false;		
	}else
	{
		//alert("not x or v");
		ctrlFlgIE = true;			
	}
  
	if(altFlg==false && ctrlFlgIE==false && yesToStartEdit==true)
	{		
		//alert("change color");
		fld=document.getElementById(event.srcElement.id);			
		fld.style.backgroundColor = "yellow";
		isDirty = true;				
	}
	
   
}

document.onkeyup = KeyCheck;


//-------------------------------------------------------------------

function kill_navigation_notification()
{
	noRequired = false;
}

//Function for arranging footer in all browser
//-------------------------------------------------------------------
function chkBrowser(){			
	
	var Opera = (navigator.userAgent.indexOf("Opera")!=-1);
	var MSIE = (navigator.appVersion.indexOf("MSIE")!=-1);
	var Moz = (navigator.userAgent.indexOf("Mozilla/5")!=-1);
	var myframe = document.getElementById("panMain");
	//alert(navigator.appVersion.indexOf("Opera"));
	//alert(MSIE);
	//alert(Moz);
		
	if (Moz)
	{
		myframe.style.height="96%";					
		myframe.style.width="99%";					
	}
	if (navigator.userAgent.indexOf("Opera")!=-1) 
	{
		hgt='96%';
		wdt='99%';
		myframe.style.height=hgt;
		myframe.style.width=wdt;
		myframe.style.bottom=0;
	}

}

//-------------------------------------------------------------------

function checkWindowUnload() {

	if (isDirty && msgDisplay==0) {
		if(noRequired==false)
		{
			//alert('no required');
			noRequired=true;
		}else
		{
			var msg = "You have not saved your changes.";
			msgDisplay=1;
			return msg;
		}
		}else
		{
		}
} 

function changeView(x,move)
{		
	var sTab = new String(x);
	location.href = changeArgs('tab', sTab)
}

function changeArgs(sArgList, sValueList) {

	var sURL = document.URL;
	var sWithout = sURL;
	
	var arrA = sArgList.split(',');
	var arrV = sValueList.split(',');
	
	for (var n=0; n < arrA.length; n++ ) {

		sArg = arrA[n];
		sValue = arrV[n];
		
		//first look for the argument preceded by a ?
		var i = sURL.indexOf('?' + sArg + '=');
		//if not found, look for it preceded by a &
		if (i == -1) { 	i = sURL.indexOf('&' + sArg + '=');	}

		if (i != -1) {
			//if either is found, get the leftmost part of the string
			var sLeft = sURL.substring(0, i);
			var x = i + sArg.length + 2
			//now get the rightmost part of the string (after the equal sign ie: "sArg=")
			var sRight = sURL.substring(x, sURL.length);
			
			//see if there are any more arguments following
			var y = sRight.indexOf('&');
			if (y == -1) {
				//if no additional arguments, then the url WITHOUT the specified parameter is the left portion (sLeft)
				sWithout = sLeft;
			} else {
				if (sLeft.indexOf('?') == -1) { 
					sLeft = sLeft + '?'; 
				} else {
					sLeft = sLeft + '&';
				}
				sWithout = sLeft + sRight.substring(y+1,sRight.length);
			}
		
		} 
		if (sWithout.indexOf('?') != -1) {
			sURL = sWithout + '&' + sArg + '=' + sValue;
		} else {
			sURL = sWithout + '?' + sArg + '=' + sValue;
		}
		
		sWithout = sURL;

	}
	
	return sURL;
}

/*
	Drop Down Menu Javascript
*/
var _version = 'Pre 1.2'; 
var unself;

if (_version != '1.2') {
    window.onerror = new Function("return true;");
}

var isNS = (navigator.appName == "Netscape");
var isMacIE = ( (navigator.userAgent.indexOf("IE 4") > -1) && (navigator.userAgent.indexOf("Mac")  > -1) );
var isDynamic = true;  ( ((document.layers && document.layers['layerTest']) || (document.all && document.all['layerTest'])) && !isMacIE );

var version = '0';
 browserName = navigator.appName;           
 browserVer = parseInt(navigator.appVersion); 
	if (browserName == "Netscape" && browserVer >= 4)version = "n4";
	else if (browserName == "Microsoft Internet Explorer" && browserVer >= 4) version = "e4";
		 
function getXCoord(imgID) {
        if (isNS) xPos = document.images[imgID].x;
        else xPos = getIEXCoord(imgID)
        return xPos;
}

function getYCoord(imgID) {
  if (isNS) yPos = document.images[imgID].y;
  else yPos = getIEYCoord(imgID);
  return yPos;
}

function getIEXCoord(imgElem) {
        xPos = eval(imgElem).offsetLeft;
        tempEl = eval(imgElem).offsetParent;
        while (tempEl != null) {
                xPos += tempEl.offsetLeft;
                tempEl = tempEl.offsetParent;
        }
        return xPos;
}

function getIEYCoord(imgElem) {
        yPos = eval(imgElem).offsetTop;
        tempEl = eval(imgElem).offsetParent;
        while (tempEl != null) {
                yPos += tempEl.offsetTop;
                tempEl = tempEl.offsetParent;
        }
        return yPos;
}


var activeMenu = 0;
function activateMenu(menuLayerRef, imageName, left, top) {		

var lightsout
    if (isDynamic && activeMenu != menuLayerRef) {    	
        if (activeMenu) hideMenu("menu" + activeMenu); 
        menuID = "menu" + menuLayerRef;
        activeMenu = menuLayerRef;
		
        if (isNS) {                	
            document.getElementById(menuID).style.left = getXCoord(imageName) + left;            
            document.getElementById(menuID).style.top = getYCoord(imageName) + top;            
        } else {            
			
            document.all(menuID).style.pixelLeft = getXCoord(imageName) + left;                        
            document.all(menuID).style.pixelTop = getYCoord(imageName) + top;            
        }
        
        showMenu(menuID, left, top)
    }
}


function showMenu(layerID, left, top) {	
   document.getElementById(layerID).style.visibility = "visible";	
}

function hideMenu(layerID) {
	document.getElementById(layerID).style.visibility = "hidden";		
    
}

// check if there's a menu active
function turnOff() {
    if (activeMenu) {
        menuID = "menu" + activeMenu;
        hideMenu(menuID);
        activeMenu = 0;
    }
}

// kills menu on clickup
function init() {
    if (isDynamic) {
        if (isNS) {
            document.captureEvents(Event.mouseup);
        }
        document.onmouseup = turnOff;
    }
}

// this function needs to be called from the sub menus DIV
function hideMe() {
    if (activeMenu) {
        menuID = "menu" + activeMenu;
        hideMenu(menuID);
        activeMenu = 0;
    }
}

// Work-around Netscape resize bug
if (isDynamic && isNS) {
    origWidth = innerWidth;
    origHeight = innerHeight;   
}
        
function reDo() {       
    if (innerWidth != origWidth || innerHeight != origHeight) {
        location.reload();
    }
}       

if (isDynamic && isNS) {
    onresize = reDo;
}

function timer(offon)  {
if (offon == 0)	{
    unself = setTimeout('turnOff()', 1200);
    }
if (offon ==1)	{
	clearTimeout(unself);
	}
}

//function for dropdown menu
activateMenu = function(nav) {

    /* currentStyle restricts the Javascript to IE only */
	if (document.all && document.getElementById(nav).currentStyle) {  
        var navroot = document.getElementById(nav);
        
        /* Get all the list items within the menu */
        var lis=navroot.getElementsByTagName("LI");  
        for (i=0; i<lis.length; i++) {
        
           /* If the LI has another menu level */
            if(lis[i].lastChild.tagName=="UL"){
            
                /* assign the function to the LI */
             	lis[i].onmouseover=function() {	
                
                   /* display the inner menu */
                   this.lastChild.style.display="block";
                   
                   /* hide any <select> controls */
                   var sel=document.getElementsByTagName("SELECT");
                   for (i=0; i<sel.length; i++) {
						sel[i].style.visibility="hidden";
                   }
                }
                lis[i].onmouseout=function() {                       
                   this.lastChild.style.display="none";
                   
                   /* show any <select> controls */
                   var sel=document.getElementsByTagName("SELECT");
                   for (i=0; i<sel.length; i++) {
 					sel[i].style.visibility="visible";
                   }
                }
            }
        }
    }
}
window.onload= function(){
    /* pass the function the id of the top level UL */
    /* remove one, when only using one menu */
    activateMenu('nav');
   // activateMenu('vertnav');    
   chkBrowser();
}



//function for use CTRL + TAB key into textArea
function CheckTab(el) {
  // Run only in IE
  // and if tab key is pressed
  // and if the control key is pressed
  if ((document.all) && (9==event.keyCode) && (event.ctrlKey)) {
    // Cache the selection
    el.selection=document.selection.createRange(); 
    setTimeout("ProcessTab('" + el.id + "')",0)
  }
}

function ProcessTab(id) {
  // Insert tab character in place of cached selection
  document.all[id].selection.text=String.fromCharCode(9)
  // Set the focus
  document.all[id].focus()
}

/*====================================================================================
Page File
====================================================================================*/

function attachPage(attach_id,attach_type){
	fOK = window.confirm('Are you sure you wish to Attach ' +  attach_type + ' with current page ?');	
	if (fOK){		
		if (attach_type == 'file') {
		
			document.all['_file_id'].value=attach_id;
			doCommand('page_file_save');
			
		} else if (attach_type == 'menu') {
			
			document.all['_menu_id'].value=attach_id;			
			doCommand('page_menu_save');
			
		}	
	}
}

function detachPage(detach_id,detach_type){
	
		if (detach_type == 'file') {
		
			document.all['_page_file_id'].value=detach_id;		
			doCommand('page_file_delete');	
			
		} else if (detach_type == 'menu') {
		
			document.all['_page_menu_id'].value=detach_id;		
			doCommand('page_menu_delete');	
			
		}	
		
}

/*====================================================================================
Contact Address Phone URL
====================================================================================*/

function setValue(objPT){				
	var primary_flag = 0;
	var type_code = 0;
	if(objPT == "") {
		primary_flag = document.getElementById('primary').value;
		type_code = document.getElementById('type_code').value;
	} else {
		primary_flag = document.getElementById('primary_' + objPT).value;
		type_code = document.getElementById('type_code_' + objPT).value;		
	}
	document.getElementById('_primary_flag').value = primary_flag;
	document.getElementById('_type_code').value = type_code;
}

function attachContact(attach_id,attach_type){
	fOK = window.confirm('Are you sure you wish to Attach ' +  attach_type + ' with current contact ?');	
	if (fOK){		
		
		//setValue(attach_id); 
		if (document.getElementById('type_code_search').value == "")
		{
			alert('Please select contact ' +  attach_type + ' type');
		} else {	
				document.all['_tie_id'].value=0;
				document.all['_type_code'].value= document.getElementById('type_code_search').value;	
				document.all['_primary_flag'].value = document.getElementById('primary_search').value;
				
			if (attach_type == 'address') {
			
				document.all['_address_id'].value=attach_id;
				
				doCommand('crm:contact_address_save');
				
			} else if (attach_type == 'phone') {
				
				document.all['_phone_id'].value=attach_id;			
				
				doCommand('crm:contact_phone_save');
				
			} else if (attach_type == 'url') {
				
				document.all['_url_id'].value=attach_id;	
				
				doCommand('crm:contact_url_save');
				
			}	
	
		}
	}
}

function detachContact(detach_id,detach_type){
		
		document.all['_tie_id'].value = detach_id;
	
		if (detach_type == 'address') {
	
			doCommand('crm:contact_address_delete');
	
		} else if (detach_type == 'phone') {
			
			doCommand('crm:contact_phone_delete');
			
		} else if (detach_type == 'url') {
			
			doCommand('crm:contact_url_delete');
			
		}	
	
}

function attachMember(attach_id){
	fOK = window.confirm('Are you sure you wish to Attach this contact with current group ?');	
	if (fOK){
		if (document.getElementById('group_status_' + attach_id).value == "")
		{
			alert('Please select contact group status');
		} else {	
				document.getElementById('_contact_id').value=attach_id;			
				document.getElementById('_group_status_id').value = document.getElementById('group_status_' + attach_id).value ;
				document.getElementById('_start_date').value = document.getElementById('start_date_' + attach_id).value ;
				doCommand('crm:group_membership_save');
		}
	}	
}

function attachGroup(group_id){
	fOK = window.confirm('Are you sure you wish to Attach this group with current contact ?');	
	if (fOK){
		if (document.getElementById('group_status_' + group_id).value == "")
		{
			alert('Please select group status');
		} else {			
				document.getElementById('_id').value=0;			
				document.getElementById('_group_status_id').value = document.getElementById('group_status_' + group_id).value ;
				document.getElementById('_start_date').value = document.getElementById('start_date_' + group_id).value ;
				doCommand('crm:contact_membership_save');
		}
	}	
}


/*====================================================================================
Portal Methods
====================================================================================*/

function minimizePortal(portal_layout_id, portal_flag) {
	document.getElementById('_portal_layout_id').value = portal_layout_id;
	document.getElementById('_portal_flag').value = portal_flag;
	doCommand('common:portal_minimize');
}

function closePortal(portal_layout_id, portal_flag) {
	
	document.getElementById('_portal_layout_id').value = portal_layout_id;
	document.getElementById('_portal_flag').value = portal_flag;
	doCommand('common:portal_close');
	
}
