var xmlHttp;

var ajaxTemplate;

var ajaxUrlVars = '';

var ajaxFormVars;

var ajaxTarget;
//sync or async ajax request
//set this one to false for a syncron request
var ajaxAsync = true;
var requestType = 'GET';
//templates for ajax calls
var ajTemlates = new Array();
//used to define what function HTTP request came from.
//the value defined withing the function
var requestSource;

var parentId;
var curLevel;
var curId;
var curAction;
var curName;
//used for feedback display in ajax calls
var fbTarget;
//hold how many levels are for the tree
var numOfLevels = 4;
//this array is temp holder for the objects that are deleted

var objDeposit = new Array();
//variable defines what to do with window after popup is closed
var	window_action ='';

//make ti 2-D

for(i=0; i<numOfLevels+1;i++){
	objDeposit[i] = new Array();
}

//list levels

var levelNames = new Array();
levelNames[0] = '';
levelNames[1] = 'agency';
levelNames[2] = 'advertiser';
levelNames[3] = 'product';
levelNames[4] = 'copy';


//the array of the links for editing and adding entities. index is the level

var editURLs = new Array();
editURLs[0] = '';
editURLs[1] = 'frm_agency.cfm';
editURLs[2] = 'frm_advertiser.cfm';
editURLs[3] = 'frm_product.cfm';
editURLs[4] = 'frm_copy.cfm';

//this array holds the history of expanded entities
//1st demension index is the level
//2nd demension holds the ids of expended levels
var treeHistory = new Array();
//make second dimension
for(var i = 1; i< numOfLevels+1; i++){
	treeHistory[i] = new Array();
}

function mm_expandTree(id,l)
{
	requestType = 'GET';
	parentId = id;
	curLevel = l;
	requestSource = 1;
	var expandId = 'treeExpand_' + l + '_' + id;
	var currentDisplay = document.getElementById(expandId).style.display;
	var plusElement = document.getElementById('tplus_' + l + '_' + id);
	document.getElementById('expandHold').value= id;
	//alert(currentDisplay)
	if(currentDisplay == 'block'){
		//remove this element from the array
		for(var x = 0; x<treeHistory[l].length;x++){
			if(treeHistory[l][x] == id){
				treeHistory[l].splice(x,1);
			}
		}
		//Effect.BlindUp($(expandId));
		document.getElementById(expandId).style.display = 'none';
		plusElement.className = 'treePlus';
		
	}
	else{
		//add to the history
		//alert("id: " + id + " l: " + l);
		treeHistory[l].push(id);
		//alert(treeHistory[l]);
		document.getElementById(expandId).style.display = 'block';
		plusElement.className = 'treeMinus';
		ajaxTemplate = 'ajax_tree.cfm';
		ajaxUrlVars = 'level=' + l + '&' + 'id=' + id;
		mm_ajaxRequest();
		
	}
	//alert(id);
	
}

//auto expand of tree based on the history
function refreshTree(ref){
	requestType = 'GET';
	ajaxAsync = false;
	//if the command is to refresh entire page when ref == 1 -- refresh the page, otherwise -- repopulated tree
	if(ref && ref == 1){
		window.location.reload();		
	}
	else{
		for(var y = 1; y < treeHistory.length; y++){
		
			for(var z = 0 ; z < treeHistory[y].length; z++){
				//reset display because treeexpand uses it as an indicator of active tree
				var expandId = 'treeExpand_' + y + '_' + treeHistory[y][z];
				//plus element
				var plusElement = document.getElementById('tplus_' + y + '_' + treeHistory[y][z]);
				//alert(document.getElementById(expandId).innerHTML);
				//document.getElementById(expandId).innerHTML = '';
				parentId = treeHistory[y][z];
				curLevel = y;
				//tplus_1_4
				//alert(expandId);
				ajaxTemplate = 'ajax_tree.cfm';
				ajaxUrlVars = 'level=' + y + '&' + 'id=' + treeHistory[y][z];
				
				//return to this feature later
				mm_ajaxRequest();
				document.getElementById(expandId).style.display = 'block';
				plusElement.className = 'treeMinus';
			}
		}
	}
	ajaxAsync = true;
}

function clickActions(id,l,act,el,parId,ref)
{
	requestType = 'POST';
	ajaxTemplate = 'ajax_actions.cfm';
	requestSource = 2;
	curId  = id;
	curLevel = l;
	curAction = act;

	switch(act)
	{
		case 'edit':
			location.href = editURLs[l] + "?" + levelNames[l] + "id=" + id + "&parentId=" + parId;
		break;   
		
		case 'duplicate':
			location.href = editURLs[l] + "?" + levelNames[l] + "id=" + id + "&parentId=" + parId + "&duplicateFlag=1";
		break;  
	
		case 'add':
			location.href = editURLs[l+1] + "?" + levelNames[l+1] + "id=0&"  + levelNames[l] + "id=" + id;
		break;
	
		case 'delete':
			ajaxFormVars = 'action=delete&entity=' + levelNames[l] + "&id=" + id;
			mm_ajaxRequest ();

		break;
		
		case 'undo':
			ajaxFormVars = 'action=undodelete&entity=' + levelNames[l] + "&id=" + id;
			mm_ajaxRequest ();
		break;
		
		case 'weight':
		//alert(levelNames[l]); 
			if(levelNames[l] == 'agency'){
				location.href = "/WeightManager/dsp_wghtmgr_agency.cfm?agencyID=" + id + "&level=" + levelNames[l];
			}
			if(levelNames[l] == 'advertiser'){
				location.href = "/WeightManager/dsp_wghtmgr_agency.cfm?advertiserID=" + id + "&level=" + levelNames[l];
			}
			if(levelNames[l] == 'product'){
				location.href = "/WeightManager/dsp_wghtmgr_agency.cfm?productID=" + id + "&level=" + levelNames[l];
			}
			//
		break;
		
		case 'negotiate':
			location.href = "dsp_copyNegotiation.cfm?CopyId=" + id;
		break;
		
		case 'active':
			var actValue = document.getElementById(levelNames[l] + "Act" + id).value;
			if(actValue == ''){
				actValue = 0;
				document.getElementById(levelNames[l] + "Act" + id).value = 0;
			}
			if(actValue*1 == 1){
				ajaxFormVars = 'action=deactivate&entity=' + levelNames[l] + "&id=" + id;
			}
			
			else{
				ajaxFormVars = 'action=activate&entity=' + levelNames[l] + "&id=" + id;
			}
			
			mm_ajaxRequest ();
			
		break;
		
		case 'viewCopy':
		
			location.href = "dsp_copySummary.cfm?CopyId=" + id + "&parentId=" + parId;
		
		break;
	}

}


function mm_ajaxRequest ()
{

  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
		xmlHttp=false;
        return false;
        }
      }
    }
	if(xmlHttp) {
	
		xmlHttp.onreadystatechange = processReqChange;
		if(requestType == 'GET'){
		//alert(ajaxFormVars);
			showFlashLoader();
			//randomGen() appends a random number to prevent browser catching
			//set new template to make each request really asyncroneous
			var sendTemplate = ajaxTemplate + '?' + ajaxUrlVars + "&" + randomGen();
			xmlHttp.open(requestType, sendTemplate, ajaxAsync);
			xmlHttp.send("");
		}
		
		else{
			showFlashLoader();
			xmlHttp.open(requestType, ajaxTemplate, ajaxAsync);
			xmlHttp.setRequestHeader("Method", requestType+ " " + ajaxTemplate + " HTTP/1.1");
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.send(ajaxFormVars);
		}
		
	}
  }
  
  
function processReqChange() {

	if (xmlHttp.readyState == 4) {
	if (xmlHttp.status == 200) {
		hideFlashLoader();
		switch(requestSource)
		{
		case 1: 
		
			document.getElementById('treeExpand_'+ curLevel + '_' + parentId).innerHTML = '';
			document.getElementById('treeExpand_'+ curLevel + '_' + parentId).innerHTML = xmlHttp.responseText;
		break  
		
		case 2:
			if(curAction == 'active')
			{
				
				var fBackTarget = document.getElementById("fBack_" + curLevel + "_" + curId);
				var actValue = document.getElementById(levelNames[curLevel] + "Act" + curId).value;
				if(actValue*1 == 1){
					
					document.getElementById(levelNames[curLevel] + "Act" + curId).value = 0;
					document.getElementById('act' + levelNames[curLevel] + curId).src = '../images/inactive1.gif';
					
					fBackTarget.innerHTML = levelNames[curLevel] == 'copy' ? 'Campaign' + ' deactivated': levelNames[curLevel] + ' deactivated';
				}
				
				else{
					if(levelNames[curLevel] == 'copy' && xmlHttp.responseText.replace(/^\s+|\s+$/g,"") == 'false'){
						alert('You have not uploaded a Creative for this Campaign.');
					}
					document.getElementById(levelNames[curLevel] + "Act" + curId).value = 1;
					document.getElementById('act' + levelNames[curLevel] + curId).src = '../images/active1.gif';
					fBackTarget.innerHTML = levelNames[curLevel] == 'copy' ? 'Campaign' + ' activated': levelNames[curLevel] + ' activated';
				}
				
			}
			
			if(curAction == 'delete')
			{
				var fBackTarget = document.getElementById("rowHolder_" + curLevel + "_" + curId);
				var entName = document.getElementById("name_" + curLevel + "_" + curId).value;
				objDeposit[curLevel][curId] = fBackTarget.innerHTML;
				var treeTarget = document.getElementById("treeExpand_" + curLevel + "_" + curId);
				treeTarget.innerHTML = '';
				treeTarget.style.display = 'none';
				
				message = '<div class="treeFeedBackWide">' + (levelNames[curLevel] == 'copy' ? 'Campaign' : levelNames[curLevel]) + ' ' + entName + ' has been <b class="bRed">DELETED</b>! Action becomes <b class="bRed">PERMANENT</b> once you leave the page!';
				message = message + ' <a href="javascript: clickActions(' + curId + ',' + curLevel + ',\'undo\')" class="treeLink">Click Here</a> To Undo Delete.';
				message = message + '<\div>';
				fBackTarget.innerHTML = message;
			}
			
			if(curAction == 'undo'){
				var fBackTarget = document.getElementById("rowHolder_" + curLevel + "_" + curId);
				fBackTarget.innerHTML = objDeposit[curLevel][curId];
				var plusDisplay = document.getElementById("tplus_" + curLevel + "_" + curId);
				if(plusDisplay){
					plusDisplay.className = 'treePlus';
				}
			}
			
			if(curAction == 'formSubmit'){
				
				fbTarget.innerHTML = xmlHttp.responseText;
				//document.getElementById('test').innerHTML = xmlHttp.responseText;
				
				
			}
			
			
			//the following is used for debugging only 
			//because the requests are silent to the client
			//document.getElementById('test').innerHTML = '';
			//document.getElementById('test').innerHTML = xmlHttp.responseText;
		break  
		}
		} else {
		hideFlashLoader();
		alert("There was a problem retrieving the data:\n" +
		xmlHttp.statusText + "Status: " + xmlHttp.status);
		var displayDiv = document.getElementById("test");
					
					displayDiv.innerHTML = xmlHttp.responseText;
		//fbTarget.innerHTML = xmlHttp.responseText;
		}
	}
}
//common functions
function randomGen(){
	var randomnumber=Math.floor(Math.random()*100000000000000000);
	return randomnumber;


}

//returns left n chars
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
//returns right n chars
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

//---------------------------- used for ajax form submit---------------------



function aj_formSubmit(f,t)
{
	submitSwitch = false;
	fbTarget = document.getElementById(t);
	
	validateForm(f);
	if(errorArray[0].length == 0){
	requestType = 'POST';
	ajaxTemplate = '/af/ajax_formSubmit.cfm';
	curAction = 'formSubmit';
	requestSource = 2;
	ajaxFormVars = '';
		for(i=0;i<f.elements.length;i++){
			if(f.elements[i].type == 'radio')
			{
				if(f.elements[i].checked){
					ajaxFormVars = ajaxFormVars + '&' + f.elements[i].name + '=' + f.elements[i].value;
				}
				
			}
			
			else
			{
				ajaxFormVars = ajaxFormVars + '&' + f.elements[i].name + '=' + f.elements[i].value;
			}
			
		}
		mm_ajaxRequest ();
	
	}



}



//-------------------- print friendly -------------------

function printFriendly()
{
	window.open('printPage.cfm','printWin','width=510,height=500,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no');

}

//this function performs whatever you wish on form field change
function onchangeActions(obj){
	var checkDefined = typeof submittable;
	if(checkDefined){
		submittable = true;
	}
	
}

//---------------------this function adjusts interrelated selects-------------------------------

function adjustSelects(fld,dep){

	var depElement = document.getElementById(dep);
	var fldHier = fld.attributes['valhierarchy'].value;
	
	if(fldHier == 'min')
	{
		if(fld.selectedIndex > depElement.selectedIndex){
			depElement.selectedIndex =  fld.selectedIndex;
		}
	}
	
	if(fldHier == 'max')
	{
		if(fld.selectedIndex < depElement.selectedIndex){
			depElement.selectedIndex =  fld.selectedIndex;
		}
	}
	

}


//trims spaces from both sides of the string
function trim(sString){


    return sString;
    
}

//formatting functions

function dollarFormat(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		{
			num = "0";
		}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		{
			cents = "0" + cents;
		}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		{
			num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
		}
	return (((sign)?'':'(') + '$' + num + '.' + cents+((sign)?'':')'));
}

/*function dollarFormat(nStr,dec,prefix){
    var prefix = prefix || '';
	var dec = dec || 2;
	//multiplier for decimals
	var multipl = '1';
	while(multipl.length < dec){
		multipl = multipl + '0';
	}
	multipl = parseInt(multipl);
    nStr = nStr.toString();
    var x = nStr.split('.');
    var x1 = x[0];
    var x2;
	if(x.length > 1){
		x2 = x[1].toString();
		if(parseInt(x2) == 0){
			x2 = '00';
		}
		
		else{
			if(x2.length < dec){
				while(x2.length < dec){
					x2 = x2 + '0';
				}
			}
			
			else if(x2.length > dec){
				var diff = x2.length - dec;
				var div = Math.pow(10,diff);
				x2 = Math.round(parseInt(x2)/div);
				x2 = x2.toString();

			}
		
		
		}
		x2 = '.' + x2;
	}
	else{
		x2 = '.00';
	}
	
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1))
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    return prefix + x1 + x2;
}*/

//finds element in the array

function testArray(ar,val){
	var flag2 = -1;
	for(var i = 0; i < ar.length;i++){
		if(ar[i] == val){
			flag2 = i;
		}
	}
	
	return flag2;
}

/*============================================================================
GLOBAL HTTPREQUEST
================================================================================

I. The Following stadard arguments have to be sent to function globalAjaxRequest:

1. requestType - ['GET'] or ['POST']
2. queryString - [url variable(s) value pairs] or [form] or [form fields values as a query string]
3. requestTemplate - [server side template to process]
4. respFunc - name of the function that will be processed upon successful request [string] 

example 1: globalAjaxRequest(['GET'], ['usertype=station&action=add'], ['dsp_addCompany.cfm'], ['showWindow']);
example 2: globalAjaxRequest(['POST'], ['usertype=station&action=add'], ['dsp_addCompany.cfm'], ['showWindow']);
example 3: globalAjaxRequest(['POST'], [form.myForm], ['dsp_addCompany.cfm'], ['showWindow']);

II. xmlHttp is a global var declared in the beginning of this template. Thus, xmlHttp.responseText is the global var too.

III. All the arguments that sent to globalAjaxRequest function are stored in a global var globalRequestArguments.
globalRequestArguments is an object that can be read via standard indexing syntax: globalRequestArguments[0...n].
globalRequestArguments can be used if more than 4 standard arguments are sent and needed to be proccessed.
*/

var globalRequestArguments = new Object();
var queryString;
var requestType;
var requestTemplate;
var respFunc;

function globalAjaxRequest (requestType, queryString, requestTemplate, respFunc)
{
	
	globalRequestArguments = globalAjaxRequest.arguments;
  try
    {
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
		xmlHttp=false;
        return false;
        }
      }
    }
	
	if(xmlHttp) {
	
	var ajaxSendVars = '';
	if(typeof(queryString) == 'object'){
			f = queryString;
			for(i=0;i<f.elements.length;i++){
				if(f.elements[i].type == 'radio')
				{
					if(f.elements[i].checked){
						ajaxSendVars = ajaxSendVars + '&' + f.elements[i].name + '=' + f.elements[i].value;
					}
				}
				//jburke// 07.18.07 Added to check for checkbox
				else if(f.elements[i].type == 'checkbox'){
					if(f.elements[i].checked){
						ajaxSendVars = ajaxSendVars + '&' + f.elements[i].name + '=' + f.elements[i].value;
					}
				}
				//disable button with property turnoff=true
				else if(f.elements[i].type == 'button' && f.elements[i].turnoff=='true'){
				f.elements[i].disabled=true;
				
				}
				else
				{  //Marina: '%26' replaces ampersand and '%25' replaces % to avoid problem when we have those symbols inside a name that is sent through URL.
						if(f.elements[i].value != null){
							ajaxSendVars = ajaxSendVars + '&' + f.elements[i].name + '=' + f.elements[i].value.replace(/%/g,"%25").replace(/&/g,"%26");						
						}
						
						
				}
				
		    }
		}
		else{
			ajaxSendVars = queryString + "&sid=" + randomGen();
		}
	
		xmlHttp.onreadystatechange = function ()
		{
			if (xmlHttp.readyState == 4) 
			{
				if (xmlHttp.status == 200) 
				{
				//hide loader
				hideFlashLoader();
				//enable buttons
					if(typeof(queryString) == 'object'){
						for(i=0;i<f.elements.length;i++){
							if(f.elements[i].type == 'button' && f.elements[i].turnoff=='true'){
								f.elements[i].disabled=false;
							}
						}
					}
				//callfunction = respFunc;
				eval(respFunc + '()');
				
				}
				else 
				{
					//hide loader
					hideFlashLoader();
					alert("There was a problem retrieving the data:\n" +
					xmlHttp.statusText + "Status: " + xmlHttp.status);
					var displayDiv = document.getElementById("test");
					if(displayDiv){
					displayDiv.innerHTML = xmlHttp.responseText;
					displayDiv.style.display = 'block';
					}
				}
			}
		}
		
		if(requestType == 'GET'){
			var fullUrl = requestTemplate + "?" + ajaxSendVars;
			xmlHttp.open("GET",fullUrl,true);
			xmlHttp.send(null);
			respondFunction = respFunc;
			showFlashLoader();
		}
		
		else{
			var fullUrl = requestTemplate;
			xmlHttp.open(requestType, fullUrl, true);
			xmlHttp.setRequestHeader("Method", requestType+ " " + requestTemplate + " HTTP/1.1");
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.send(ajaxSendVars);
			showFlashLoader();
		}
	}
  }
  //this function shows and hides flash loader
  function showFlashLoader(){
  	//see if the element exists on the page
	var loaderDiv = document.getElementById("flashLoader");
	var loaderDivFull = document.getElementById("flashLoaderFull");
	//it it exists - make it visible
	if(loaderDiv){
		loaderDiv.style.display = "block";
	}
	if(loaderDivFull){
		loaderDivFull.style.display = "block";
	}
  }
    
  //function to hide flash loader
  function hideFlashLoader(){
  //see if the element exists on the page
	var loaderDiv = document.getElementById("flashLoader");
	var loaderDivFull = document.getElementById("flashLoaderFull");
	//if it exists - make it invisible
	if(loaderDiv){
		loaderDiv.style.display = "none";
	}
	if(loaderDivFull){
		loaderDivFull.style.display = "none";
	}
  
  }
  
  /*
  *	function ajaxDummy
  *	@param	none
  *	
  *	an empty function in case no action needs to be performed on requestchange
  */
  
  function ajaxDummy(){
  	//just do nothing
  }
  
  function advertiserRelocate(){
 		ajaxPopup();
  }
  
  function ajaxRelocate(){
	window.location.href = xmlHttp.responseText;  
  }
  
  //END OF GLOBAL REQUEST================================================================================
  
  /* The function that opens main popup div and populates it with a content via AJAX request
  
  */
  
function ajaxPopup(){

	var displayDiv = document.getElementById("messageDisplay");
	var displayMsg = document.getElementById("messageHTML");
	var displayBtm = document.getElementById('messageBottomBorder');
	//document.getElementById("test").innerHTML = xmlHttp.responseText;
	displayMsg.innerHTML = xmlHttp.responseText;
	
	if(globalRequestArguments.length > 4){
		displayDiv.style.width = globalRequestArguments[4] + 'px';
		displayBtm.width = eval(globalRequestArguments[4] - 20);
	}

	displayDiv.style.display = 'block';
	document.getElementById('screen').style.display = 'block';
}

function ajaxPopupAdmin(){

	var displayDiv = document.getElementById("messageDisplay");
	var displayMsg = document.getElementById("messageHTML");
	var displayBtm = document.getElementById('messageBottomBorder');
	//document.getElementById("test").innerHTML = xmlHttp.responseText;
	displayMsg.innerHTML = xmlHttp.responseText;
	
	if(globalRequestArguments.length > 4){
		displayDiv.style.width = globalRequestArguments[4]+'px';
		displayBtm.width = eval(globalRequestArguments[4] - 20);
	}
	if(globalRequestArguments.length > 5){
		window_action = globalRequestArguments[5];
	}
	displayDiv.style.display = 'block';
	document.getElementById('screen').style.display = 'block';

}


function ajaxPopClose(){
	var displayDiv = document.getElementById("messageDisplay");
	var displayMsg = document.getElementById("messageHTML");
	displayMsg.innerHTML = "";
	displayDiv.style.display = 'none';
	document.getElementById('screen').style.display = 'none';
	submitSwitch = true; //return this variable to default
 	if (window_action=='refreshAdmin'){
		//window.location.reload( true );
		if(document.forms['companyList']){
		document.forms['companyList'].submit();
		}
	}
	if (window_action=='reloadAgencyOptions'){
	globalAjaxRequest('GET', 'companytype=agency', 'ajax_Company.cfm', 'getNewOptions');
	}
	if (window_action=='reloadAdvertiserOptions'){
	globalAjaxRequest('GET', 'companytype=advertiser', 'ajax_Company.cfm', 'getNewOptions');
	}
	if (window_action=='reloadPolAdvertiserOptions'){
	globalAjaxRequest('GET', 'companytype=poladvertiser', 'ajax_Company.cfm', 'getNewOptions');
	}
	if (window_action=='reloadAAM'){
		if (document.getElementById("agencyID")){
		    //page called from add user page
			var agencyid = document.getElementById("agencyID").value;
			querystring = "getAdvertisers=1&agencyid="+agencyid;
			}
		else{
		    //page called from edit user page
			history.go(0);
		}
	
	globalAjaxRequest('GET',querystring,'/admin/ajax_createUser.cfm','getAdvertisersDisplay');
	}
	if (window_action=='reloadPage'){
		history.go(0);
	}
}

function edited(){	
	document.getElementById("test").innerHTML = xmlHttp.responseText;
	//displayMsg.innerHTML = xmlHttp.responseText;

}

/*======================================================================================================
The following function populates US city and state based on the zip entered
through ajax request.
The function validates zip entry and sends request as the length of zip reaches 5 characters.
All plug-ins should be done onKeyUp
========================================================================================================*/

function getUSZip(el,cityField,stateField){
	//el is the form input object
	//cityField,stateField are strings of Ids for the city and state input fields in teh form
	//replace all non-numerical chars and spaces
	el.value = el.value.replace(/[^0-9,-]/g,"");
	//send request when length is 5
	if(el.value.toString().length == 5){
		
		requestType = 'GET';
		requestTemplate = '/ajaxCFM/ajax_getzip.cfm';
		queryString = 'action=uszip&postVar=' + el.value;
		respFunc =  'getUSZipResponce';
		globalAjaxRequest (requestType, queryString, requestTemplate, respFunc,el.form[cityField],el.form[stateField],el.form);
	}
}
//this proccesses ajax responce sent by getUSZip function
function getUSZipResponce(){
	
	var respArray = xmlHttp.responseText.split("|");
	if(parseInt(respArray[2]) > 0){
		//write town name
		globalRequestArguments[4].value = respArray[4];
		//select state in drop down
		for(var i = 0; i < globalRequestArguments[5].options.length; i++){
			if(globalRequestArguments[5].options[i].value == respArray[5]){
				globalRequestArguments[5].selectedIndex = i;
			}
		}

	}
	

}

// Nav location	
	function nav_location(winLoc) {
		//alert(winLoc);
		// alert(winLoc.indexOf('.'));
		//Stations.startLoading()
		var levelFind = winLoc.indexOf('.');
		if(levelFind >= 0) {
			var levelGet = winLoc.split('.');
			var levelUrl = levelGet[1];
		} else {
			var levelUrl = winLoc;
		}
		var url='';
		var t = this.title || this.name || null;
		var g = this.rel || false;
		switch(levelUrl) {
			// ** Contact Us **
			case 'contact':
				location.href = '/contactus/contactus.cfm';
			break
			// ** Help **
			case 'Help':
			    location.href = "##";
			    t="MCS Help";
			    url='/dsp_help.cfm?keepThis=true&TB_iframe=true&height=400&width=800'; 
                TB_show(t,url,g);return false;	
			break;			
			// ** Logout **
			case 'logout':
				location.href = '/login/logout.cfm';
			break
			// ** Profile **
			case 'profile':
				location.href = '/admin/dsp_editUser.cfm';
			break
			/* 
			 * ** Reports ** 
			 */
			
			// Client Budget Report
			case 'clientBudget':
				location.href = '/reports/rpt_clientBudgetReport.cfm?leftnav=advreport.nav';
			break
			// User Login Report
			case 'userLogin':
				location.href = '/reports/rpt_userLogin.cfm?leftnav=genreport.nav';
			break
			//  Cut Report
			case 'emcscut':
				location.href = '/reports/rpt_emcsCut.cfm?leftnav=genreport.nav';
			break
			// Registration Report
			case 'registration':
				location.href = '/reports/rpt_registration.cfm?leftnav=genreport.nav';
			break
			// ROI Report
			case 'roimap':
				location.href = '/Agency/ROIMap/rpt_ROImap.cfm?leftnav=advreport.nav';
			break
			// Products By Station Report
			case 'pbystation':
				location.href = '/reports/rpt_productsByStation.cfm?leftnav=stareport.nav';
			break
			// Products By Station Report based on Orders
			case 'pbystationorders':
				location.href = '/reports/rpt_productsByStationOrders.cfm?leftnav=stareport.nav';
			break
			// Station Order History Report
			case 'soh':
				location.href = '/reports/rpt_stationOrderHistory.cfm?leftnav=stareport.nav';
			break
			// Stations By Agency Report
			case 'sbyagency':
				location.href = '/reports/rpt_stationsByAgency.cfm?leftnav=advreport.nav';
			break
			// Stations By Advertiser Report
			case 'sbyadvertiser':
				location.href = '/reports/rpt_stationsByAdvertiser.cfm?leftnav=advreport.nav';
			break
			// Stations By Advertiser Report based on Orders
			case 'sbyadvertiserorders':
				location.href = '/reports/rpt_stationsByAdvertiserOrders.cfm?leftnav=advreport.nav';
			break
			//Advertiser Order History Report
			case 'aoh':
				location.href = '/reports/rpt_advertiserOrderHistory.cfm?leftnav=advreport.nav';
			break
			// Station Pricing Report
			case 'pricingreport':
				location.href = '/reports/rpt_stationPricing.cfm?leftnav=stareport.nav';
			break
			// Spot Load Report
			case 'spotload':
				location.href = '/reports/rpt_spotLoad.cfm?leftnav=stareport.nav';
			break
			// ** Administrator **
			// Manage Stations
			case 'station':
				location.href = '/admin/dsp_companyList.cfm?companyType=Station&leftnav=admin.nav';
			break
			// Manage Agencies
			case 'agency':
				location.href = '/admin/dsp_companyList.cfm?companyType=Agency&leftnav=admin.nav';			
			break
			// Manage Advertisers
			case 'advertiser':
				location.href = '/admin/dsp_companyList.cfm?companyType=Advertiser&leftnav=admin.nav';			
			break
			// Manage Users
			case 'user':
				location.href = '/admin/dsp_UsersList.cfm?leftnav=admin.nav';
			break
			// Admin Tools
			case 'adminTool':
				location.href = '/admin/dsp_makeChangesTool.cfm?leftnav=admin.nav';
			break
			// Manage Weights 
			case 'weightman':
				location.href = '/WeightManager/dsp_wghtmgr_agency.cfm?leftnav=admin.nav';
			break
			// Manage User Groups
			case 'userGroup':
				location.href = '/admin/dsp_customPermGroups.cfm?leftnav=admin.nav';
			break
			// Edit Settings
			case 'editSettings':
				location.href = '/admin/form_customheader.cfm?leftnav=admin.nav';
			break
			
			// ** Accounting **
			case 'ledger':
				location.href= '/accounting/ledger/dsp_ledger.cfm?leftnav=account.nav';
			break
			case 'invoice':
				location.href= '/accounting/dsp_invoiceGen.cfm?leftnav=account.nav';
			break			
			// ** Media Manager **
			case 'mediaManager':
				location.href= '/MediaManager/';
			break
			// ** Wizard **
			case 'wizard':
				location.href = "##";
			    url='/Agency/wizard.cfm?keepThis=true&TB_iframe=true&height=400&width=500'; 
                t="Quick Setup";
                TB_show(t,url,g);return false;
			break
			// ** Agency DashBoard **
			case 'agencyDashBoard':
				location.href= '/dsp_agency_dashboard.cfm';
			break
			
			// ** Stations **
			case 'viewStation':
				location.href = '/Station/';
			break
			case 'viewBroadcast':
				location.href = '/Station/dsp_broadcaster_dashboard.cfm';
			break
			case 'orders':
			    location.href = "##";
			    url='/Station/dsp_newOrders.cfm?keepThis=true&TB_iframe=true&height=400&width=800'; 
                t="Orders";
                TB_show(t,url,g);return false;
				
			break
			case 'history':
				location.href ="##";
				t="History";
			    url= '/Station/dsp_OrderHistory.cfm?keepThis=true&TB_iframe=true&height=400&width=800';
			    TB_show(t,url,g);return false;
			break
			case 'inventory':
				location.href ="##";
				t="Inventory";
			    url= '/Station/dsp_inventory.cfm?keepThis=true&TB_iframe=true&height=400&width=800';
			    TB_show(t,url,g);return false;
			break 
			case 'flights':
				location.href ="##";
			    url= '/Station/dsp_Flighted.cfm?keepThis=true&TB_iframe=true&height=400&width=800';
			    TB_show(t,url,g);return false;
			break
			case 'spread':
				location.href ="##";
				url= '/Station/dsp_spreadReport.cfm?keepThis=true&TB_iframe=true&height=400&width=800';
				t="Spread";
				TB_show(t,url,g);return false;
			break
			case 'standBy':
				location.href = "##";
				t="Insertion Orders";
			    url= '/Station/dsp_StandByInsertOrder.cfm?keepThis=true&TB_iframe=true&height=400&width=800';
			    TB_show(t,url,g);return false;
			break
			case 'postLogs':
				location.href = "##";
				t="Post Log";
			    url= '/Station/dsp_Postings.cfm?keepThis=true&TB_iframe=true&height=600&width=750';
			    TB_show(t,url,g);return false;
			break
			
 			// ** Home **
			default:
				location.href = '/index.cfm';

			      

		}
	}
	// Drill down or drop down nav menu
	function nav_toggle(el)	{
		var Obj = $(el);
		if( Obj.visible()) {
	   // Effect.SlideUp($(el));
			new Effect.Parallel([new Effect.BlindUp(Obj,{sync:true})],{afterFinish: function(){$(el).hide();}});
//	     document.getElementById(el).style.display = 'none';
		} else { 
			new Effect.Parallel([new Effect.BlindDown(Obj,{sync:true})],{afterFinish: function(){$(el).show();}});
	     //document.getElementById(el).style.display = 'block';
	   }
	}
	
	//jburke// functions used to move from one select box to the other when optgroups are involved
	var moveFunctions = {
		moveWithGroup: function(box1,box2){
			fBox = document.getElementById(box1);
			tBox = document.getElementById(box2);
			permlist = document.getElementById('selectedperms').value;
						
			//remove any unruly children
			for(i = 0; i < fBox.getElementsByTagName('optgroup').length; i++){
				for(x = 0; x < fBox.getElementsByTagName('optgroup')[i].childNodes.length; x++){
					if(isNaN(fBox.getElementsByTagName('optgroup')[i].childNodes[x].value)){
						fBox.getElementsByTagName('optgroup')[i].removeChild(fBox.getElementsByTagName('optgroup')[i].childNodes[x]);
					}
				}
			}
			
			//move items
			for(i = 0; i < fBox.length; i++){
				if(fBox.options[i].selected){
					//lock the default values
					if(permlist.indexOf('.'+fBox.options[i].value+'.') < 0){
						var group = fBox.options[i].parentNode;
						var found = false;
						for(x = 0; x < tBox.length; x++){
							if(tBox.options[x].parentNode.id == group.id){
								found = true;
								var optgroup = tBox.options[x].parentNode;
							}		
						}
						if(found == false){
							var optgroup = document.createElement('optgroup');
							optgroup.id = group.id;
							optgroup.label = group.label;
							tBox.appendChild(optgroup);
						}
						optgroup.appendChild(fBox.options[i]);
						i = i - 1;
					}
					else {
						alert('This permission is locked. You cannot remove it.')
					}
				}
			}
			
			// clean up groups
			for(i = 0; i < fBox.getElementsByTagName('optgroup').length; i++){
				if(fBox.getElementsByTagName('optgroup')[i].childNodes.length == 0){
					fBox.removeChild(fBox.getElementsByTagName('optgroup')[i]);
					i = i - 1;
				}
			}
		},
		moveNoGroup: function(box1,box2){
			fBox = document.getElementById(box1);
			tBox = document.getElementById(box2);
						
			//move items
			for(i = 0; i < fBox.length; i++){
				if(fBox.options[i].selected){
					tBox.appendChild(fBox.options[i]);
					i = i - 1;
				}
			}
		}
	};
	
	
/* Check if session is expired. In 7260000 (2 hours and 1 min) mlsec send a request to server and asks if session is expired.
			If expired page is relocated to the page login/dsp_sessionExpired.cfm*/
window.setInterval('sendrequest()', 7260000);

function sessioncheck(){
//document.getElementById("test").innerHTML = xmlHttp.responseText;
	expired=xmlHttp.responseText;
	if (expired==1){
	 window.location.href="../login/dsp_sessionExpired.cfm";
	}
}
function sendrequest(){
        var page = (location.pathname.indexOf('?') != -1) ? location.pathname.substring(0, location.pathname.indexOf('?')) : location.pathname;
        var bypassedpages = new Array();
		bypassedpages[0] = "/index.cfm";
		bypassedpages[1] = "/login/dsp_noPageAccess.cfm";
		bypassedpages[2] = "/login/act_login.cfm";
		bypassedpages[3] = "/login/act_resetPassword.cfm";
		bypassedpages[4] = "/login/alreadyLoggedin.cfm";
		bypassedpages[6] = "/login/eula.cfm";
		bypassedpages[7] = "/login/fn_loginMod.cfm";
		bypassedpages[9] = "/login/forgotPassword.cfm";
		bypassedpages[11] = "/login/loggedIn.cfm";
		bypassedpages[12] = "/login/login.cfm";
		bypassedpages[13] = "/login/logout.cfm";
		bypassedpages[14] = "/login/resetPassword.cfm";
		bypassedpages[16] = "/login/secretQuestion.cfm";
		bypassedpages[17] = "/admin/dsp_Registration.cfm";
		bypassedpages[18] = "/admin/act_Registration.cfm";
		bypassedpages[19] = "/admin/ajax_Verification.cfm";	
        bypassedpages[20] = "/admin/ajax_uniqueCheck.cfm"; 
        bypassedpages[21] = "/admin/dsp_ThankYou.cfm";	
		bypassedpages[22] = "/login/checkSession.cfm";	
		bypassedpages[23] = "/login/ajax_checkSession.cfm";	
		bypassedpages[24] = "/login/dsp_sessionExpired.cfm";
		bypassedpages[25] = "/privacy.cfm";
		bypassedpages[26] = "/tos.cfm";
		bypassedpages[27] = "/aboutus.cfm";
		bypassedpages[28] = "/contacts.cfm";
	var pathfound = 0;
	for(var i = 0; i < bypassedpages.length; i++){
		if(page == bypassedpages[i]){ pathfound=1;}
	}
		if(pathfound==0){
			globalAjaxRequest('GET', 'usertype=station&page='+page, '../login/ajax_checkSession.cfm','sessioncheck');
		}
}

//Marina: show arbitron subscribed books for adveertiser
function showBooks(id)
{
	window.open('dsp_arbBooks.cfm?id='+id,'bookWin','width=500,height=500,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no');

}
/*ending code for checking if session is expired*/

/** Import Copy Block */
var ImportCopy = {
	/** Build the window and form.
	 *  @param (int) productid Product for which to import a copy.
	 */
	buildDisplay:function(productid){
		/** if the window is not created, create it and the form */
		if(!win){
			/** form used for uploading the xml. */
			var uploadform = new Ext.form.FormPanel({
				name:'XMLCopyForm',
				id:'XMLCopyForm',
				fileUpload:true,
				method:'POST',
				url:'/customtags/AJAXGateway/JSONGateway.cfm?comp=ImportCampaign&method=UploadCopyXML&productid='+productid,
				items:[
					new Ext.form.Field({
						inputType:'file',
						id:'XMLCopy',
						name:'XMLCopy',
						fieldLabel:'File'
					})
				]
			});
			
			/** popup window used to upload the file */
			var win = new Ext.Window({
				layout:'form',
				modal:true,
				name:'UploadWindow',
				id:'UploadWindow',
				title:'Import Copy',
				width:350,
				height:90,
				buttons:[
					/** Upload Button */
					{
						text:'Upload',
						handler:function(){
							/** there is a file specified to upload */
							if(uploadform.form.findField('XMLCopy').getValue().length > 0) {
								uploadform.form.submit({
									waitMsg:'Uploading, please wait...',
									success:function(f,ac){
										var tfile = ac.result.filelocation;
										var tcopy = ac.result.copyid;
										var tproduct = ac.result.productid;
										ImportCopy.parseCopy(tfile,tproduct,tcopy);
										win.close();
									},
									failure:function(f,ac){
										alert('No data to process.')
										win.close();
									}
								})
							}
							/** ask that a file be selected */
							else{
								alert('Please select a file to upload.');
							}
						}
					},
					/** Close Button */
					{
						text:'Close',
						handler:function(){win.close();}
					}
				]
			});
		}
		/** show the window and form */
		win.show();
		uploadform.render(win.body);
	},
	/** Displays a confirmation box to ask if you wish to overwrite data.
	 * 	Then sends request to parse the data if so desired.
	 *  @param (string) fileloc File to parse.
	 *  @param (int) productid Product for which to import a copy.
	 *  @param (int) copyid Copy to overwrite if not 0.
	 */
	parseCopy:function(fileloc,productid,copyid){
		/** state whether or not to overwrite the campaign */
		var overwrite = 0;
		
		/** Copy ID is not 0, we could overwrite */
		if(copyid != 0){
			/** Confirmation box */
			Ext.Msg.show({
				title:'Overwrite?',
				msg: 'Would you like to overwrite your existing Campaign?',
				buttons: Ext.Msg.YESNOCANCEL,
				/** check which button was pressed and take appropriate action */
				fn: function(btn,text){
					if(btn == 'yes'){
						overwrite = 1;
					}
					else if(btn == 'no'){
						copyid = 0;
						overwrite = 0;
					}
					else{
						Ext.Msg.close();
						return true;
					}
					/** Processing box */
					Ext.Msg.wait('Parsing data, please wait');
					/** Ajax request to parse the data and place in tables */
					Ext.Ajax.request({
						url:'/customtags/AJAXGateway/JSONGateway.cfm',
						params:{
							comp:'ImportCampaign',
							method:'ReadCopyXML',
							xmlfile:fileloc,
							productid:productid,
							overwrite:overwrite,
							copyid:copyid
						},
						method:'GET',
						/** request returned response, redirect to the media manager */
						success:function(a){
							Ext.Msg.hide();
							var resp = Ext.decode(a.responseText);
							window.location.href = resp.RETURL;
						},
						/** no response */
						failure:function(a){
							Ext.Msg.hide();
							alert('The data was not parsed properly.');
						}
					});
				},
				icon: Ext.MessageBox.QUESTION
			});
		}
		/** New Copy, Parse data via AJAX request */
		else{
			/** Processing box */
			Ext.Msg.wait('Parsing data, please wait');
			/** Ajax request to parse the data and place in tables */
			Ext.Ajax.request({
				url:'/customtags/AJAXGateway/JSONGateway.cfm',
				params:{
					comp:'ImportCampaign',
					method:'ReadCopyXML',
					xmlfile:fileloc,
					productid:productid
				},
				method:'GET',
				/** request returned response, redirect to the media manager */
				success:function(a){
					Ext.Msg.hide();
					var resp = Ext.decode(a.responseText);
					window.location.href = resp.RETURL;
				},
				/** no response */
				failure:function(a){
					alert('The spots were not saved.');
				}
			})
		}
	}
}

function	setActive(lvl,id,act,el){
				if(parseInt(Ext.getDom(lvl+'Act'+id).value)==1)
						actn = 'activate'
				else
						actn = 'deactivate'		
				Ext.Ajax.request({
				   url: '/MediaManager/ajax_actions.cfm',
				   success: function(){
					   	if(Ext.getDom(lvl+'Act'+id).value == 0){
					   	   Ext.getDom(el).src='/images/status/tick.png'
					   	   Ext.getDom(lvl+'Act'+id).value=1;
					   	} 
					   	else{
					   	   Ext.getDom(el).src='/images/status/cross.png'
					   	   Ext.getDom(lvl+'Act'+id).value=0;
				   		}  
				   },
				   failure: function(r){
				   	document.body.innerHTML=r.responseText
				   	
				   },
				   params: { 
				   	entity:lvl, // Agency,advertiser,product,copy
				   	id: id,// id of above 
				   	action:act // what to do
				   	}
				});

	}