// Generic Control function s

	//#### BROWSER DETECT ####
	// to use, call : browser = "", OS = "", etc
	
	var detect = navigator.userAgent.toLowerCase();
	var OS,browser,version,total,thestring;

	if (checkIt('konqueror'))
	{
		browser = "Konqueror";
		OS = "Linux";
	}
 	else if (checkIt('netscape')) browser = "Netscape Navigator";
	else if (checkIt('safari')) browser = "Safari";
	else if (checkIt('omniweb')) browser = "OmniWeb";
	else if (checkIt('opera')) browser = "Opera";
	else if (checkIt('webtv')) browser = "WebTV";
	else if (checkIt('icab')) browser = "iCab";
	else if (checkIt('msie')) browser = "Internet Explorer";
	else if (checkIt('firefox')) browser = "Mozilla Firefox";
	else if (!checkIt('compatible'))
	{
		browser = "Mozilla"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version)
	{
		version = detect.charAt(place + thestring.length);
	}

	if (!OS)
	{
		if (checkIt('linux')) OS = "Linux";
		else if (checkIt('x11')) OS = "Unix";
		else if (checkIt('mac')) OS = "Mac"
		else if (checkIt('win')) OS = "Windows"
		else OS = "an unknown operating system";
	}

	function checkIt(string)
	{
		place = detect.indexOf(string) + 1;
		thestring = string;
		return place;
	}

//### CONFIRMATION function s ####
//Confiim deactivate
function confirmDeactivate(campaign,advertiser)
{
	return confirm("You are about to deactivate the campaign ["+campaign+"] from the advertiser ["+advertiser+"]. ARE YOU SURE?");
}

//### CONFIRMATION function s ####
//Confiim deactivate
function confirm_delete(msg)
{

	return confirm(msg);
}

function confirmAcctDel(network,market,user,level)
{
	if(level == "network")
	{
		var agree=confirm("You are about to delete the ["+network+"] network and everything associated with this network. ARE YOU SURE?");
	}
	if(level == "market")
	{
		var agree=confirm("You are about to delete the ["+network+"] ["+market+"] market and everything associated with this market. ARE YOU SURE?");
	}
	if(level == "user")
	{
		var agree=confirm("You are about to delete ["+network+"] ["+market+"] ["+user+"]. ARE YOU SURE?");
	}
	if (agree)
	{
		return true;
	}
	else
	{
		return false ;
	}
}

function confirmCategoryDel(category,name)
{
	var agree=confirm("You are about to delete "+category+" ["+name+"]. ARE YOU SURE?");
	if (agree)
	{
	}
	else
	{
		return false ;
	}
}


//### Image function s ####
//universal get object
function findObj(n, d)
{
	//v4.01
 	var p,i,x; if(!d) d=document;
 	
 	if((p=n.indexOf("?"))>0&&parent.frames.length)
	{
 		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
 	}
 	
 	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
 	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
 	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

//preload images (body tag or solo script)
function preloadImages()
{
	var d=document;
	
	if(d.images)
	{
		if(!d.p) d.p=new Array();
	
 		var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
 		if (a[i].indexOf("#")!=0)
		{
			d.p[j]=new Image; d.p[j++].src=a[i];
		}
	}
}
//call on mouse out
function swapImgRestore()
{
	var i;
	var x,a=document.sr;
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
	{
		x.src=x.oSrc;
	}
}

function swapImage()
{
	var i,j=0,x,a=swapImage.arguments;
	document.sr=new Array;
	for(i=0;i<(a.length-2);i+=3)
	{
		if ((x=findObj(a[i]))!=null)
		{
			document.sr[j++]=x;
			if(!x.oSrc)
			{
				x.oSrc=x.src;
			}
			x.src=a[i+2];
		}
	}
}
function remove(s, t)
{
	/*
	** Remove all occurrences of a token in a string
	** s string to be processed
	** t token to be removed
	** returns new string
	*/
	i = s.indexOf(t);
	r = "";
	if (i == -1)
	{
		return s;
	}
	
	r += s.substring(0,i) + remove(s.substring(i + t.length), t);
	
	return r;
}

function swap_nav_image(id, item_state)
{
	image_name = document.getElementById("image_" + id).src;

	if(image_name.indexOf("MO") > -1)
	{
		if(item_state == 0)
		{
			image_name = remove(image_name, "MO");
		}
	}
	else
	{
		cut_loc = image_name.indexOf(".gif");

		if(cut_loc > -1)
		{
			image_name = image_name.substring(0,cut_loc) + "MO" + image_name.substr(cut_loc)
		}
	}

	document.getElementById("image_" + id).src = image_name;

}

function swap_nav_class(id)
{
	class_name = document.getElementById("div_" + id).className;

	if(class_name.indexOf("active") > -1)
	{
		return;
	}

	if(class_name.indexOf("_over") > -1)
	{
		cut_loc = class_name.indexOf("_over");
		class_name = class_name.substring(0,cut_loc);

	}
	else
	{
		class_name = class_name + "_over";
	}

	document.getElementById("div_" + id).className = class_name;

}

//generic popup window
function openWindow(url, name, width, height)
{
window.open(url,name,'width='+width+',height='+height+',top=200,left=200,scrollbars=no');
}

//#### Layer function s ####
//make layerName visible
function showLayer(layerName)
{
	itemname = document.getElementById(layerName);

	if(itemname)
	{
		itemname.style.display = 'block';
	}
	else
	{
		//alert(layerName);
	}
}

//make layerName hidden
function hideLayer(layerName)
{
	itemname = document.getElementById(layerName);
	if(itemname)
	{
		itemname.style.display = 'none';
	}
	else
	{
		//alert(layerName);
	}
}

//toggle LayerName on/off
function toggleLayer(L1,L2,L3)
{
	L1 = L1;
 	L2 = L2;
 	L3 = L3;

	itemname = document.getElementById(L1+L2+L3);

	if(itemname)
	{
		//Turn on the main BG and row tags
		if(itemname.style.display == 'block')
		{
			itemname.style.display = 'none';
		}
		else
		{
			itemname.style.display = 'block';
		}
	}
	else
	{
		//alert(L1+L2+L3);
	}
}

/*
	toggle
		1	mouse in
		0	mouse out
*/
function header_over(element_name, toggle)
{
	//	0	- "expand"
	//	1	- color - blue, green, etc
	//	2	- plus or minus
	//	3	- may = MO
	img_element = document.getElementById(element_name);
	
	if(!img_element)
	{
		return false;
	}

	name_position = img_element.src.lastIndexOf("/")+1;
	full_path = img_element.src.substr(0, name_position);
	assigned_image = img_element.src.substr(name_position);
	last_index = assigned_image.lastIndexOf('.jpg');
	assigned_image = assigned_image.substr(0, last_index);

	ar_fields = assigned_image.split("_");

	full_path = full_path + ar_fields[0] + "_" + ar_fields[1] + "_" +  ar_fields[2];
	
	if(toggle == 1)
	{
		full_path = full_path + "_MO";
	}
	
	full_path = full_path + ".jpg";

	img_element.src = full_path;	
}

//sets the buttons from + to - for the exp
function swapTabs(element_name)
{
	//	0	- "expand"
	//	1	- color - blue, green, etc
	//	2	- plus or minus
	//	3	- may = MO
	img_element = document.getElementById(element_name);
	
	if(!img_element)
	{
		return false;
	}

	name_position = img_element.src.lastIndexOf("/")+1;
	full_path = img_element.src.substr(0, name_position);
	assigned_image = img_element.src.substr(name_position);
	last_index = assigned_image.lastIndexOf('.jpg');
	assigned_image = assigned_image.substr(0, last_index);

	ar_fields = assigned_image.split("_");
	
	if(ar_fields[2] == "plus")
	{
		ar_fields[2] = "minus";
	}
	else
	{
		ar_fields[2] = "plus";
	}

	full_path = full_path + ar_fields[0] + "_" + ar_fields[1] + "_" +  ar_fields[2];
	
	if(ar_fields[3])
	{
		full_path = full_path + "_MO";
	}
	
	full_path = full_path + ".jpg";

	img_element.src = full_path;	
}

//Background swap for expansion parts
function swapBg(element_name)
{
	img_element = document.getElementById(element_name);
	
	if(!img_element)
	{
		return false;
	}

	name_position = img_element.style.backgroundImage.lastIndexOf("/") + 1;

	//name_position = img_element.style.backgroundImage.lastIndexOf("/")+1;
	full_path = img_element.style.backgroundImage.substr(0, name_position);
	assigned_image = img_element.style.backgroundImage.substr(name_position);
	last_index = assigned_image.lastIndexOf('.jpg');
	assigned_image = assigned_image.substr(0, last_index);

	ar_fields = assigned_image.split("_");
	
	if(ar_fields[2] == "expanded")
	{
		ar_fields[2] = "collapsed";
	}
	else
	{
		ar_fields[2] = "expanded";
	}

	full_path = full_path + ar_fields[0] + "_" + ar_fields[1] + "_" +  ar_fields[2];
	
	full_path = full_path + ".jpg)";
	
	//alert(full_path);

	img_element.style.backgroundImage = full_path;

}

function grayOut(vis)
{
	// Pass true to gray out screen, false to ungray
 	var zindex = 50;
 	var opacity = vis;
 	var opaque = (opacity / 100);
 	var bgcolor = '#000000';
 	var dark=document.getElementById('darkenScreenObject');
 	if (!dark)
	{
 		var tbody = document.getElementsByTagName("body")[0];
 		var tnode = document.createElement('div');
 		tnode.style.position='absolute';
 		tnode.style.top='0px';
 		tnode.style.left='0px';
 		tnode.style.overflow='hidden';
 		tnode.style.display='none';
 		tnode.id='darkenScreenObject';
 		tbody.appendChild(tnode);
 		dark=document.getElementById('darkenScreenObject');
 	}
 	if (vis)
	{
 		// Calculate the page width and height
 		if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
		{
 var pageWidth = document.body.scrollWidth+'px';
 var pageHeight = document.body.scrollHeight+'px';
 }
else if( document.body.offsetWidth )
{
 var pageWidth = document.body.offsetWidth+'px';
 var pageHeight = document.body.offsetHeight+'px';
 }
else
{
 var pageWidth='100%';
 var pageHeight='100%';
 }
 //set the opacity
 dark.style.opacity=opaque;
 dark.style.MozOpacity=opaque;
 dark.style.filter='alpha(opacity='+opacity+')';
 dark.style.zIndex=zindex;
 dark.style.backgroundColor=bgcolor;
 dark.style.width= pageWidth;
 dark.style.height= pageHeight;
 dark.style.display='block';
 }
else
{
	 dark=parent.document.getElementById('darkenScreenObject');
 dark.style.display='none';
 }
}

//#### Ajax expansion juitsu ####

please_wait = "<span class='orange'><b>&nbsp;Loading...</b></span>";

function detectAJAX()
{

	if (!document.getElementById)
{
 		return false;
 	}

 	if (window.ActiveXObject)
	{
 		link = new ActiveXObject("Microsoft.XMLHTTP");
 	}
	else if (window.XMLHttpRequest)
	{
 		link = new XMLHttpRequest();
 	}

 	if (link == undefined)
	{
 		return false;
 	}

}

function getAJAX()
{

	if (!document.getElementById)
	{
 		return null;
 	}

 	if (window.ActiveXObject)
	{
 		link_item = new ActiveXObject("Microsoft.XMLHTTP");
 	}
	else if (window.XMLHttpRequest)
	{
 		link_item = new XMLHttpRequest();
 	}

 	if (link_item == undefined)
	{
 		return null;
 	}

 	return link_item;

}

// ########## PLAYER MANAGEMENT FUNCTION S ##########
function open_plr(url,target,functionType,functionVal)
{

	detectAJAX();

	if (target != null)
	{
 		document.getElementById(target).innerHTML = please_wait;
 	}

 	link.onreadystatechange = function ()
{ response(url, target); }
 	link.open("POST", url+"?functionType="+functionType+"&functionVal="+functionVal, true);
	link.send(null);
}

// ########## TMA ADVERTISER FUNCTION S ##########
function open_url(url,network,market,advertiser,level,target,quickview,page,ad_name)
{
	detectAJAX();

	//alert(target);

	if(target != null)
	{
 		document.getElementById(target).innerHTML = please_wait;
 	}

 	link.onreadystatechange = function ()
{ response(url, target); }
 	link.open("POST", url+"?network="+network+"&market="+market+"&advertiser="+advertiser+"&level="+level+"&quickview="+quickview+"&page="+page+"&ad_name="+ad_name, true);
	link.send(null);
}

// ########## for obtaining NETWORK / MARKET /CALLS ##########
function open_add_calls(url,target,network,market,call_letters,level)
{

	detectAJAX();

	if (target != null)
	{
 		document.getElementById(target).innerHTML = please_wait;
 	}

	if(target)
	{
		link.onreadystatechange = function ()
		{
			response(url, target);
		}
	}

	link.open("POST", url+"?network="+network+"&market="+market+"&call_letters="+call_letters+"&level="+level, true);
	link.send(null);
}
function call_server_sync(target_element_name, aparams)
{
	if(!target_element_name)
	{
		return;
	}

	target_element = document.getElementById(target_element_name);

	if(!target_element)
	{
		return false;
	}

	AJAX = getAJAX();
	
	url = build_URL(aparams);

 	if (AJAX)
	{
 		AJAX.open("POST", url, false);
 		AJAX.send(null);
 		document.getElementById(target_element_name).innerHTML = AJAX.responseText;
 		return true;
 	}
	else
	{
 		return false;
 	}
}
/*
	target_element
		target DIV element
	aparms
		Object containing the params being passed to the server
	fn_call_back
		the function to call when this request returns

*/

function call_server(target, aparams, fn_call_back)
{
	if(!target)
	{
		return;
	}

	target_element = document.getElementById(target);

	if(!target_element)
	{
		return false;
	}

	link_item = getAJAX();

 	url = build_URL(aparams);
 	
 	//alert(link_item);
 	
 	call_back_item = new Object();
 	
 	//link_item.send_to_element = Object();
 	call_back_item.target_element = target;
 	call_back_item.fn_call_back = server_response;

	if(fn_call_back)
	{
		call_back_item.fn_call_back = fn_call_back;
	}
 	
	link_item.onreadystatechange = function ()
	{
		//alert(call_back_item);
		call_back_item.link_item = link_item;
		call_back_item.fn_call_back();
	}

	link_item.open("POST", url, true);
	link_item.send(null);
}

//GENERIC RESPONDER
function server_response()
{
	if (this.link_item.readyState == 4)
	{
		//alert('in here');
		document.getElementById(this.target_element).innerHTML = (this.link_item.status == 200) ? this.link_item.responseText : "<span class='defaultText'>Error! Data Unavailable. Errorcode: " + this.link_item.status + "</span>";
	}
}

//--------------------------------------------------------------------------
/**
	\brief
		Builds the URL which we'll request from the server.
	\param
	\return
*/
//--------------------------------------------------------------------------
function build_URL(aParams)
{
	//	The params which are being passed onto the server
	//	strURL is the location file we're calling
	var strParams;
	var strURL;

	strURL = "";
	strParams = "";
	/*
		Cycle through our list of values and send them to the server
	*/
	for (var i in aParams)
	{
		/*
			Location is the base of the URL string.
			It should be our only hardcoded value
		*/
		if (i == 'location')
		{
			/*
				Make the url match was is held in the location parameter
			*/
			strURL = aParams[i] + ".php?";
		}
		else
		{
			strParams += i + "=" + encodeURIComponent(aParams[i]) + "&";
		}
	}

	strURL += strParams;

	return strURL;
}


// ########## for obtaining NETWORK / MARKET /CALLS ##########
function add_user_calls(url,target,network,market,call_letters, level)
{
	detectAJAX();
	if(target)
	{
		document.getElementById(target).innerHTML = please_wait;
		link.onreadystatechange = function ()
{ response(url, target); }
	}

	link.open("POST", url+"?network="+network+"&market="+market+"&level="+level+"&call_letters="+call_letters, true);
	link.send(null);

	return true;
}

// ########## STREAMADZ (IMPRESSION ALERTS) ##########
function open_streamadz(url,network,market,advertiser,level,target,quickview,page,ad_name,advertiserID)
{

	detectAJAX();

	 if (please_wait != null)
{
 		document.getElementById(target).innerHTML = please_wait;
 	}
	//alert(advertiser);
 	link.onreadystatechange = function ()
{ response(url, target); }
 	link.open("POST", url+"?network="+network+"&market="+market+"&advertiser="+advertiser+"&level="+level+"&quickview="+quickview+"&page="+page+"&ad_name="+ad_name+"&advertiserID="+advertiserID, true);
	link.send(null);
}

//GENERIC RESPONDER
function response(url, target)
{
	if (link.readyState == 4)
	{
		document.getElementById(target).innerHTML = (link.status == 200) ? link.responseText : "<span class='defaultText'>Error! Data Unavailable. Errorcode: " + link.status + "</span>";
	}
}

//TIERED RESPONDER
function tiered_respose(url, target, nextfunction )
{
 	if (link.readyState == 4)
{
	 	document.getElementById(target).innerHTML = (link.status == 200) ? link.responseText : "<span class='defaultText'>Error! Data Unavailable. Errorcode: " + link.status + "</span>";
		if(nextfunction )
{
		eval(nextfunction +"();");
		}
	}
}

function emailCheck (emailStr)
{
	/* The following pattern is used to check if the entered e-mail address
	 fits the user@domain format. It also is used to separate the username
	 from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	 characters. We don't want to allow special characters in the address.
	 These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a
	 username or domainname. It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	 which case, there are no rules about which characters are allowed
	 and which aren't; anything goes). E.g. "jiminy cricket"@disney.com
	 is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	 rather than symbolic names. E.g. joe@[123.124.233.4] is a legal
	 e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	 non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	 For example, in john.doe@somewhere.com, john and doe are words.
	 Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	 domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	/* Finally, let's start trying to figure out if the supplied address is
	 valid. */

	if(emailStr.length < 1)
	{
		alert("Please Enter a Valid Email");
		return false;
	}

	/* Begin with the coarse pattern to simply break up user@domain into
	 different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null)
	{
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid
	if (user.match(userPat)==null)
	{
		// user is not valid
		alert("Please Enter a Valid Email");
		return false
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	 host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null)
	{
		// this is an IP address
		for (var i=1;i<=4;i++)
		{
			if (IPArray[i]>255)
			{
			alert("Please Enter a Valid Email");
			return false
			}
		}
		return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null)
	{
		alert("Please Enter a Valid Email");
		return false
	}

	/* domain name seems valid, but now make sure that it ends in a
	 three-letter word (like com, edu, gov) or a two-letter word,
	 representing country (uk, nl), and that there's a hostname preceding
	 the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	 it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
	{
		// the address must end in a two letter or three letter word.
		alert("Please Enter a Valid Email");
		return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2)
	{
		alert("Please Enter a Valid Email");
		return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}
function ValidWebsite(value)
{

	// Examples that work:
	// http://www.example.com/
	// http://www.example.com:8080/
	// http://www.example.com/directory/
	// http://www.example.com/directory/subdirectory/
	// http://www.example.com/directory/subdirectory/page.html
	// http://www.example.com/directory/subdirectory/page.html#Anchor
	// http://www.example.com/directory/subdirectory/exec.php?search_term=whatnot
	// http://www.example.com/directory/subdirectory/exec.php?search_term=whatnot&search_type=video
	// https://www.example.museum:8080/directory/subdirectory/exec.php?search_term=whatnot&search_type=video&client=Firefox#Anchor

	// Yes, it is complicated. URLs usually are.
	return /^(http|https|HTTP|HTTPS):\/\/[A-Za-z0-9\-.]+\.([A-Za-z]{2}|biz|com|edu|info|name|net|org|pro|aero|asia|cat|coop|edu|gov|int|jobs|mil|mobi|museum|tel|travel)(:[0-9]+)?(\/[A-Za-z0-9\/\-_.]*)?(\?([^&=]+(=[^&=]*))(&[^&=]+(=[^&=]*))*)?(#[A-Za-z][A-Za-z0-9\-_:.]*)?$/.test(value);
}

function show_element(element_name)
{
	if(document.getElementById(element_name))
	{
		document.getElementById(element_name).style.display="block";
	}	
}

function hide_element(element_name)
{
	if(document.getElementById(element_name))
	{
		document.getElementById(element_name).style.display="none";
	}	
}
function set_value(element_name, element_value)
{
	if(document.getElementById(element_name))
	{
		document.getElementById(element_name).value = element_value;
	}	
}
function get_value(element_name, default_value)
{
	if(document.getElementById(element_name))
	{
		return document.getElementById(element_name).value;
	}
	
	return "";
}
function disable_element(element_name)
{
	if(document.getElementById(element_name))
	{
		document.getElementById(element_name).disabled = true;
	}	
}
function enable_element(element_name)
{
	if(document.getElementById(element_name))
	{
		document.getElementById(element_name).disabled = false;
	}	
}
function disable_element(element_name)
{
	if(document.getElementById(element_name))
	{
		document.getElementById(element_name).disabled = true;
	}	
}
