/*
 * This file will be minimized so feel free to comment liberally
 *
 */
var ov_clicked = false;
var ov_timeout;
var ov_title;
var ov_term;
var ov_defs = new Array();



/** supress errors if no jquery */
try{if($);}catch(jqe){
	function cht(){}
	cht.prototype.ready=function(a){}
	$ = function(){return new cht()};
}


/*
 * ONLY PUT STUFF HERE THAT SHOWS UP ON ALMOST EVERY PAGE
 */
$(document).ready(function(){
	fixToolTips();
	jQuery.each($('a.click_track'), clickTrackHref); 
});


/*
 * so all the ajax calls behave the same
 *
 * tgt - ajax target url
 * error - error function, use ignore if you don't care
 * success - success function
 */
function stAjax(tgt, error, success){
	if(root_path == null) root_path = "/";
	var rpTgt = root_path+tgt;
	
	try{
	    $.ajax({
	            url: rpTgt,
	            type: 'GET',
	            dataType: 'text',
	            cache: false,
	            timeout: 20000,
	            error: error,
	            success: success
	    });
	}catch(err){
		stFailure("stAjax:"+tgt+":"+err);
	}
}

/*
 * so all the ajax calls behave the same
 *
 * tgt - ajax target url
 * error - error function, use ignore if you don't care
 * success - success function
 */
function stSyncAjax(tgt, error, success){
	if(root_path == null) root_path = "/";
	//var rpTgt = root_path+tgt;
	try{
	    $.ajax({
	            url: tgt,
	            async: false,
	            type: 'GET',
	            dataType: 'text',
	            cache: false,
	            timeout: 20000,
	            error: error,
	            success: success
	    });
	}catch(err){
		stFailure("stSyncAjax"+tgt+":"+err);
	}
}

function stFailure(err){
	try{
		consoleError(err);
	    $.ajax({
	            url: "/ajax_click?page=js_error&ct="+err,
	            type: 'GET',
	            dataType: 'text',
	            cache: false,
	            timeout: 20000
	    });
	}catch(err2){}
}



// dont do nothin
function ignore(){}


// tool tip and glossary cluetip config parameters
var CLUTIP_ARGS = {
	dropShadow:'true',
	activation:'click',
	dropShadowSteps:'4',
	CloseText:'Close',
	closePosition:'title',
	cursor:'pointer',
	sticky:'true'};


/*
 * filter out anything that has already been cluetip'd
 */
function ctFilter(index){
	var ret = !$(this).hasClass("ctpd")
	if(ret)$(this).addClass("ctpd");
	return ret;
}

/*
 * ajax content needs to have tooltips initialized after drawing
 *
 */
function fixToolTips(){
	if(root_path == null) root_path = "/";
	jQuery.each($('a.tooltip'), function(){
		var r = this.rel;
		if(!r.match("ajax_glossary"))this.rel = root_path+"ajax_glossary?grp=tooltip&term="+this.rel;
		this.href = "javascript:;";
	});
	jQuery.each($('a.glossary'), function(){
		var r = this.rel;
		if(!r.match("ajax_glossary"))this.rel = root_path+"ajax_glossary?grp=glossary&term="+this.rel;
		this.href = "javascript:;";
	});
	$('a.tooltip').filter(ctFilter).cluetip(CLUTIP_ARGS);
	$('a.glossary').filter(ctFilter).cluetip(CLUTIP_ARGS);
}


//
// replace the href with onclick and click track
//
function clickTrackHref(){
	//this is the window we will open
	var hr = this.href;
	//call the original onclick too
	var oc = this.onclick;
	this.href="javascript:;"
	this.onclick=function(){
		try{
			consoleLog("clicked:"+this.id);
			if(typeof(clicked) == "function"){
				clicked(this.id);
			}else{
				stFailure("clicked not defined for page:"+window.location);
			}
			if(typeof(oc) == "function")oc();
			window.open(hr);
		}catch(err){
			stFailure("clickTrackHref failed page:"+err+":"+window.location);
		}
	};
}

var lastOVGClass;

// fade ovg + log ajax click
// creating function to allow crownpeak to use
function ajaxFOVGL(dest, p, ct) { 
	stAjax("ajax_click?page="+p+"&ct="+ct, ignore, ignore);
	ajaxFadeOvg(dest);
}

// *open the ovg and then fade out on hide
// *dest = request url
// *return false not necessary
function ajaxFadeOvg(dest) {
	try{
		stAjax(
			dest,
			ignore,
			function(xhr){ fadeOvgLyt(xhr, null);}
		);
	}catch(e){
		stFailure("AJAX FADE OVG ERR:"+e);
	}
}

//open the ovg after making an ajax call
//str: ajax url
//clz: override display class
function ajaxOvg(str, clz){
	stAjax(
		str,
		ignore, 
		function(xml){
			ovg(xml);
		 }
	);
}

//open the ovg after making an ajax call
//str: ajax url
//clz: override display class
function ajaxSOvg(str, clz){
	stSyncAjax(
		str,
		ignore, 
		function(xml){
			ovg(xml);
		 }
	);
}

function fadeOvgLyt(val, btn) { 
	var fadeOVG = function(hash) { 
		hash.w.fadeOut('400',function(){ hash.o.remove(); }); 
	};
	$('#ovgLyt').html(val);
	if (btn != null) $('#ovgLyt-href').html(btn)
	else $('#ovgLyt-href').css("display", "none");
	if($.fn.bgiframe){
		$('#ovgLyt').jqm({overlay: 40, onHide: fadeOVG}).bgiframe().jqmShow();
	}else{
		$('#ovgLyt').jqm({overlay: 40, onHide: fadeOVG}).jqmShow();
	}
}

function ovgLyt(val, btn){
	$('#ovgLyt-inner').html(val);
	if (btn != null) $('#ovgLyt-href').html(btn);
	if($.fn.bgiframe){
		$('#ovgLyt').jqm({overlay: 40}).bgiframe().jqmShow();
	}else{
		$('#ovgLyt').jqm({overlay: 40}).jqmShow();
	}
}

function ovgHide(){
	$('#ovg').jqm().jqmHide();
}

function ovg(val, clz){
	if(lastOVGClass != null)$("#ovg_overlay").removeClass(lastOVGClass);
	lastOVGClass = clz;
	if(clz != null)$("#ovg_overlay").addClass(clz);
	$('#ovg-content').html(val);

	if($.fn.bgiframe){
		$('#ovg').jqm({overlay: 40}).bgiframe().jqmShow();
	}else{
		$('#ovg').jqm({overlay: 40}).jqmShow();
	}
}

function ovgHide(){
	$('#ovg').jqm().jqmHide();
}

function ovgnc(val){
	$('#ovgnc-content').html(val);
	if($.fn.bgiframe){
		$('#ovgnc').jqm({overlay: 40}).bgiframe().jqmShow();
	}else{
		$('#ovgnc').jqm({overlay: 40}).jqmShow();
	}
}

function ovgncHide(){
	$('#ovgnc').jqm().jqmHide();
}


function ovgPI(val){
	$('#ovgPI-content').html(val);
	if($.fn.bgiframe){
		$('#ovgPI').jqm({overlay: 40}).bgiframe().jqmShow();
	}else{
		$('#ovgPI').jqm({overlay: 40}).jqmShow();
	}
}

function ovgncHide(){
	$('#ovgPI').jqm().jqmHide();
}

// This is for the error modal that pops up on the search widget
function ovgErr(val){
	$('#ovgErr-content').html(val);
	$('#ovgErr').jqm({overlay: 40}).jqmShow();
}

function ovgErrHide(){
	$('#ovgErr').jqm().jqmHide();
}

function toggleHeaderContent(headerId, containerId){
	consoleLog("toggleContainerHeader hdr:"+headerId+" cnt:"+containerId);
	$('#'+headerId).toggleClass("hdr-open");
	$('#'+headerId).toggleClass("hdr-close");
	$('#'+containerId).toggle();
}


function toggleDisplay(id) {
	consoleLog("toggleDisplay id:"+id);
	$('#'+id).toggle();
}

function scrollToAnchor(anchorId){
	var coord = getAnchorPosition(anchorId);
	window.scroll(coord.x,coord.y);
}


/** TAB MENU SCRIPT **/
function changeTabSection(curSection, sections){
	var onClass = "tabOn";
	var offClass = "tabOff";

    for (var i=0; i<sections.length; i++) {
        section = sections[i];
        viewable = section == curSection ? true : false;
        el = document.getElementById(section + "Button");
        el.className = viewable ? onClass : offClass;
    }
	tabItem(curSection,0);
}

/** TAB MENU SCRIPT **/
function changeTabSectionScroll(curSection, sections, anchorId){
	changeTabSection(curSection, sections);
	scrollToAnchor(anchorId);	
}


function tabItem(tab, item){
	document.getElementById('item_text').innerHTML = document.getElementById('src_'+tab+'_'+item).innerHTML;
	try{
		if(changeTabSectionCallback)changeTabSectionCallback();
	}catch(err){}
}
/** END TAB MENU SCRIPT **/

function newWindow(wurl, o_height, w_height){
	stWindow=window.open(wurl,'peWin', 'WIDTH=' + o_height + ',HEIGHT=' + w_height + ',SCROLLBARS=yes, resizable=yes');
	stWindow.focus();
}

// THIS IS TO CLEAR THE FOCUS OF A TEXT FIELD
function clearValue(el) {
  if (el.defaultValue==el.value) el.value = ""
}

function sendEmail(emailLink) {
	window.open(emailLink,'preWnd','width=500,height=600,scrollbars=yes,menubar=no,resizable=yes');
}

function printPage(target) {
	var newWindow = window.open(target, 'printWindow', 'width=750,height=600,scrollbars=yes,menubar=no,resizable=yes');
}

function openGlossaryWindow() {
	newWindow('/glossary', 820, 500);
}


function popup(title, hnd, under, width, height)
{
	winfeatures = "width=" + width + ",height=" + height + ",scrollbars=yes,menubar=no,resizable=yes";
	win2 = window.open("/popup?hnd=" + hnd, title, winfeatures)
	if (under) {
		win2.blur()
		window.focus()
	}
}


// ----------------------------------------------------------------------------
// CLICK TO CALL MOVED FROM RESULTS TO DETAILS AND CC CAN USE IT
function clickCall(id){
	ajaxOvg('click_to_call?a=t&id='+id);
}

// ----------------------------------------------------------------------------
// CREATED - DF-01/11/2008
// GENERIC POPUP WINDOW REDIRECT
// YOU CAN PLACE THIS ON AN ONCLICK AND TARGET THE PARENT WINDOW
// BEHAVIOR - POPUP WILL CLOSE AND PARENT WINDOW WILL LOAD THE SPECIFIC PAGE ASKED FOR
function popupRedirect(url,closeIt,delay){
    opener.location.href = url;
	if (closeIt == true)setTimeout('self.close()',delay);
}

// ----------------------------------------------------------------------------
// CREATED - 01/11/2008
// GENERIC TAB CHANGE
function changeTab(src,id,clz){
	$("."+clz).hide();
	$("#"+src+id).show();
	$(".tab").removeClass("on");
	$("#tab"+id).addClass("on");
}

function dropSession(){
	var rnd = Math.random()*100000;
	stAjax("remove_session?r=f&rsrnd="+rnd, ignore, ignore);
}

function recentView(val){
	try{
		stAjax(
			"recent_view?hnd="+val,
			ignore,
			function(xml){populateRV(xml);}
		);
	}catch(rverr){stFailure("recentView:"+rverr);}
}

function populateRV(xml){
	$("#rv_view div.bx-content").html(xml);
	$(".recent-view").show();
}

function consoleLog(str){
	if(consoleOK()){
		console.log(str);
	}
}

function consoleError(str){
	if(typeof(console) == "object" && typeof(console.log) == "function"){
		console.error(str);
	}
}

function consoleOK(){
	if(typeof(min_js) == "string" && min_js == "false" && typeof(console) == "object" && typeof(console.log) == "function"){
		return true;
	}else{
		return false;
	}
}


// THE FOLLOWING SCRIPT IS USED FOR THE CROWN PEAK TEXT SIZE INCREASE.
function changeFontSize(inc)
{
	//var size_f = parseFloat($("div.col2 p").css("font-size"), $('html').css('font-size'));
	var size_f = parseFloat($("div.col2 li").css("font-size"), $('html').css('font-size'));
	var scale = 1 + (inc*0.2);
	$("div.col2 p").css("font-size", size_f*scale);
	$("div.col2 li").css("font-size", size_f*scale);
}

function comStatsCallback(data, text){
	$("#"+data.cs.cs_id).html(data.cs.div_body);
}
function comStatsClick(id, action, p){
	callJSON({
	url: "com_stats_click?cs_id="+id+"&action="+action+"&p="+p+"&callback=?",
	success: comStatsCallback
	});
}
