//General
//for example: instead of each module writing out script found in moduleMaxMin_OnClick have the functionality cached
//

var TOP_COL_DELIMITER = String.fromCharCode(16);
var TOP_ROW_DELIMITER = String.fromCharCode(15);
var __top_m_bPageLoaded = false;

window.onload = __top_Page_OnLoad;

function __top_ClientAPIEnabled()
{
    return typeof(top) != 'undefined' && !!top.getVar;
}


function __top_Page_OnLoad()
{
	if (__top_ClientAPIEnabled())
	{
		var sLoadHandlers = top.getVar('__top_pageload');
		if (sLoadHandlers != null)
			eval(sLoadHandlers);
		
		top.dom.attachEvent(window, 'onscroll', __top_bodyscroll);
	}
	__top_m_bPageLoaded = true;
}

function __top_KeyDown(iKeyCode, sFunc, e)
{
	if (e == null)
		e = window.event;

	if (e.keyCode == iKeyCode)
	{
		eval(unescape(sFunc));
		return false;
	}
}

function __top_bodyscroll() 
{
	var oF=document.forms[0];	
	if (__top_ClientAPIEnabled() && __top_m_bPageLoaded)
		oF.ScrollTop.value=document.documentElement.scrollTop ? document.documentElement.scrollTop : top.dom.getByTagName("body")[0].scrollTop;
}

function __top_setScrollTop(iTop)
{
	if (__top_ClientAPIEnabled())
	{
		if (iTop == null)
			iTop = document.forms[0].ScrollTop.value;
	
		var sID = top.getVar('ScrollToControl');
		if (sID != null && sID.length > 0)
		{
			var oCtl = top.dom.getById(sID);
			if (oCtl != null)
			{
				iTop = top.dom.positioning.elementTop(oCtl);
				top.setVar('ScrollToControl', '');
			}
		}
		window.scrollTo(0, iTop);
	}
}

//Focus logic
function __top_SetInitialFocus(sID)
{
	var oCtl = top.dom.getById(sID);	
	if (oCtl != null && __top_CanReceiveFocus(oCtl))
		oCtl.focus();
}	

function __top_CanReceiveFocus(e)
{
	//probably should call getComputedStyle for classes that cause item to be hidden
	if (e.style.display != 'none' && e.tabIndex > -1 && e.disabled == false && e.style.visible != 'hidden')
	{
		var eParent = e.parentElement;
		while (eParent != null && eParent.tagName != 'BODY')
		{
			if (eParent.style.display == 'none' || eParent.disabled || eParent.style.visible == 'hidden')
				return false;
			eParent = eParent.parentElement;
		}
		return true;
	}
	else
		return false;
}

//Max/Min Script
function __top_ContainerMaxMin_OnClick(oLnk, sContentID)
{
	var oContent = top.dom.getById(sContentID);
	if (oContent != null)
	{
		var oBtn = oLnk.childNodes[0];
		var sContainerID = oLnk.getAttribute('containerid');
		var sCookieID = oLnk.getAttribute('cookieid');
		var sCurrentFile = oBtn.src.toLowerCase().substr(oBtn.src.lastIndexOf('/'));
		var sMaxFile;
		var sMaxIcon;
		var sMinIcon;

		if (top.getVar('min_icon_' + sContainerID))
			sMinIcon = top.getVar('min_icon_' + sContainerID);
		else
			sMinIcon = top.getVar('min_icon');

		if (top.getVar('max_icon_' + sContainerID))
			sMaxIcon = top.getVar('max_icon_' + sContainerID);
		else
			sMaxIcon = top.getVar('max_icon');

		sMaxFile = sMaxIcon.toLowerCase().substr(sMaxIcon.lastIndexOf('/'));

		var iNum = 5;
		if (oLnk.getAttribute('animf') != null)
			iNum = new Number(oLnk.getAttribute('animf'));
			
		if (sCurrentFile == sMaxFile)
		{
			oBtn.src = sMinIcon;				
			//oContent.style.display = '';
			top.dom.expandElement(oContent, iNum);
			oBtn.title = top.getVar('min_text');
			if (sCookieID != null)
			{
				if (top.getVar('__top_' + sContainerID + ':defminimized') == 'true')
					top.dom.setCookie(sCookieID, 'true', 365);
				else
					top.dom.deleteCookie(sCookieID);
			}
			else
				top.setVar('__top_' + sContainerID + '_Visible', 'true');
		}
		else
		{
			oBtn.src = sMaxIcon;				
			//oContent.style.display = 'none';
			top.dom.collapseElement(oContent, iNum);
			oBtn.title = top.getVar('max_text');
			if (sCookieID != null)
			{
				if (top.getVar('__top_' + sContainerID + ':defminimized') == 'true')
					top.dom.deleteCookie(sCookieID);
				else
					top.dom.setCookie(sCookieID, 'false', 365);				
			}
			else
				top.setVar('__top_' + sContainerID + '_Visible', 'false');			
		}
		
		return true;	//cancel postback
	}
	return false;	//failed so do postback
}

function __top_Help_OnClick(sHelpID)
{
	var oHelp = top.dom.getById(sHelpID);
	if (oHelp != null)
	{
		if (oHelp.style.display == 'none')
			oHelp.style.display = '';
		else
			oHelp.style.display = 'none';

		return true;	//cancel postback
	}
	return false;	//failed so do postback
}

function __top_SectionMaxMin(oBtn, sContentID)
{
	var oContent = top.dom.getById(sContentID);
	if (oContent != null)
	{
		var sMaxIcon = oBtn.getAttribute('max_icon');
		var sMinIcon = oBtn.getAttribute('min_icon');
		var bCallback = oBtn.getAttribute('userctr') != null;
		var sVal;
		if (oContent.style.display == 'none')
		{
			oBtn.src = sMinIcon;				
			oContent.style.display = '';
			if (bCallback)
			    sVal = 'True';
			else
			    top.setVar(oBtn.id + ':exp', 1);
		}
		else
		{
			oBtn.src = sMaxIcon;				
			oContent.style.display = 'none';
			if (bCallback)
			    sVal = 'False';
			else
                top.setVar(oBtn.id + ':exp', 0);
		}
		if (bCallback)
		    topcore.setUserProp(oBtn.getAttribute('userctr'), oBtn.getAttribute('userkey'), sVal, null);
		return true;	//cancel postback
	}
	return false;	//failed so do postback
}

//Drag N Drop
function __top_enableDragDrop()
{
	var aryConts = top.getVar('__top_dragDrop').split(";");	
	var aryTitles;

	for (var i=0; i < aryConts.length; i++)
	{
		aryTitles = aryConts[i].split(" ");
		if (aryTitles[0].length > 0)
		{			
			var oCtr = top.dom.getById(aryTitles[0]);
			var oTitle = top.dom.getById(aryTitles[1]);
			if (oCtr != null && oTitle != null)
			{
				oCtr.setAttribute('moduleid', aryTitles[2]);
				top.dom.positioning.enableDragAndDrop(oCtr, oTitle, '__top_dragComplete()', '__top_dragOver()');
			}	
		}
	}
}

var __top_oPrevSelPane;
var __top_oPrevSelModule;
var __top_dragEventCount=0;
function __top_dragOver()
{
	__top_dragEventCount++;
	if (__top_dragEventCount % 75 != 0)	//only calculate position every 75 events
		return;
	
	var oCont = top.dom.getById(top.dom.positioning.dragCtr.contID);

	var oPane = __top_getMostSelectedPane(top.dom.positioning.dragCtr);
		
	if (__top_oPrevSelPane != null)	//reset previous pane's border
		__top_oPrevSelPane.pane.style.border = __top_oPrevSelPane.origBorder;

	if (oPane != null)
	{		
		__top_oPrevSelPane = oPane;
		oPane.pane.style.border = '4px double ' + TOP_HIGHLIGHT_COLOR;
		var iIndex = __top_getPaneControlIndex(oCont, oPane);

		var oPrevCtl;
		var oNextCtl;
		for (var i=0; i<oPane.controls.length; i++)
		{
			if (iIndex > i && oPane.controls[i].id != oCont.id)
				oPrevCtl = oPane.controls[i];
			if (iIndex <= i && oPane.controls[i].id != oCont.id)
			{
				oNextCtl = oPane.controls[i];
				break;
			}
		}			
		
		if (__top_oPrevSelModule != null)
			top.dom.getNonTextNode(__top_oPrevSelModule.control).style.border = __top_oPrevSelModule.origBorder;
			

		if (oNextCtl != null)
		{
			__top_oPrevSelModule = oNextCtl;
			top.dom.getNonTextNode(oNextCtl.control).style.borderTop = '5px groove ' + TOP_HIGHLIGHT_COLOR;
		}
		else if (oPrevCtl != null)
		{
			__top_oPrevSelModule = oPrevCtl;
			top.dom.getNonTextNode(oPrevCtl.control).style.borderBottom = '5px groove ' + TOP_HIGHLIGHT_COLOR;
		}
	}
}

function __top_dragComplete()
{
	var oCtl = top.dom.getById(top.dom.positioning.dragCtr.contID);
	var sModuleID = oCtl.getAttribute('moduleid');
	
	if (__top_oPrevSelPane != null)
		__top_oPrevSelPane.pane.style.border = __top_oPrevSelPane.origBorder;

	if (__top_oPrevSelModule != null)
		top.dom.getNonTextNode(__top_oPrevSelModule.control).style.border = __top_oPrevSelModule.origBorder;
		
	var oPane = __top_getMostSelectedPane(top.dom.positioning.dragCtr);
	var iIndex;
	if (oPane == null)
	{
		var oPanes = __top_Panes();
		for (var i=0; i<oPanes.length; i++)
		{
			if (oPanes[i].id == oCtl.parentNode.id)
				oPane = oPanes[i];
		}
	}	
	if (oPane != null)
	{
		iIndex = __top_getPaneControlIndex(oCtl, oPane);
		__top_MoveToPane(oPane, oCtl, iIndex);

		top.callPostBack('MoveToPane', 'moduleid=' + sModuleID, 'pane=' + oPane.paneName, 'order=' + iIndex * 2); 
	}
}

function __top_MoveToPane(oPane, oCtl, iIndex)
{

	if (oPane != null)
	{
		var aryCtls = new Array();
		for (var i=iIndex; i<oPane.controls.length; i++)
		{
			if (oPane.controls[i].control.id != oCtl.id)
				aryCtls[aryCtls.length] = oPane.controls[i].control;

			top.dom.removeChild(oPane.controls[i].control);
		}
		top.dom.appendChild(oPane.pane, oCtl);
		oCtl.style.top=0;
		oCtl.style.left=0;
		oCtl.style.position = 'relative';
		for (var i=0; i<aryCtls.length; i++)
		{
			top.dom.appendChild(oPane.pane, aryCtls[i]);
		}
		__top_RefreshPanes();
	}
	else
	{
		oCtl.style.top=0;
		oCtl.style.left=0;
		oCtl.style.position = 'relative';
	}
}

function __top_RefreshPanes()
{
	var aryPanes = top.getVar('__top_Panes').split(';');
	var aryPaneNames = top.getVar('__top_PaneNames').split(';');
	__top_m_aryPanes = new Array();
	for (var i=0; i<aryPanes.length; i++)
	{
		if (aryPanes[i].length > 0)
			__top_m_aryPanes[__top_m_aryPanes.length] = new __top_Pane(top.dom.getById(aryPanes[i]), aryPaneNames[i]);
	}
}

var __top_m_aryPanes;
var __top_m_aryModules;
function __top_Panes()
{
	if (__top_m_aryPanes == null)
	{
		__top_m_aryPanes = new Array();
		__top_RefreshPanes();
	}
	return __top_m_aryPanes;
}

function __top_Modules(sModuleID)
{
	if (__top_m_aryModules == null)
		__top_RefreshPanes();
	
	return __top_m_aryModules[sModuleID];
}

function __top_getMostSelectedPane(oContent)
{
	var oCDims = new top.dom.positioning.dims(oContent);
	var iTopScore=0;
	var iScore;
	var oTopPane;
	for (var i=0; i<__top_Panes().length; i++)
	{
		var oPane = __top_Panes()[i];
		var oPDims = new top.dom.positioning.dims(oPane.pane);
		iScore = top.dom.positioning.elementOverlapScore(oPDims, oCDims);
		
		if (iScore > iTopScore)
		{
			iTopScore = iScore;
			oTopPane = oPane;
		}
	}
	return oTopPane;
}

function __top_getPaneControlIndex(oContent, oPane)
{
	if (oPane == null)
		return;
	var oCDims = new top.dom.positioning.dims(oContent);
	var oCtl;
	if (oPane.controls.length == 0)
		return 0;
	for (var i=0; i<oPane.controls.length; i++)
	{
		oCtl = oPane.controls[i];
		var oIDims = new top.dom.positioning.dims(oCtl.control);
		if (oCDims.t < oIDims.t)
			return oCtl.index;
	}
	if (oCtl != null)
		return oCtl.index+1;
	else
		return 0;
}

//Objects
function __top_Pane(ctl, sPaneName)
{
	this.pane = ctl;
	this.id = ctl.id;
	this.controls = new Array();
	this.origBorder = ctl.style.border;
	this.paneName = sPaneName;
	
	var iIndex = 0;
	var strModuleOrder='';
	for (var i=0; i<ctl.childNodes.length; i++)
	{
		var oNode = ctl.childNodes[i];
		if (top.dom.isNonTextNode(oNode))	
		{
			if (__top_m_aryModules == null)
				__top_m_aryModules = new Array();

			//if (oNode.tagName == 'A' && oNode.childNodes.length > 0)
			//	oNode = oNode.childNodes[0];	//TOP now embeds anchor tag 
				
			var sModuleID = oNode.getAttribute('moduleid');
			if (sModuleID != null && sModuleID.length > 0)
			{
				strModuleOrder += sModuleID + '~';
				this.controls[this.controls.length] = new __top_PaneControl(oNode, iIndex);
				__top_m_aryModules[sModuleID] = oNode.id;
				iIndex+=1;
			}
		}
	}
	this.moduleOrder = strModuleOrder;

}

function __top_PaneControl(ctl, iIndex)
{
	this.control = ctl;
	this.id = ctl.id;
	this.index = iIndex;
	this.origBorder = ctl.style.border;
	
}

//move towards topcore ns.  right now only for personalization
function __topcore()
{
    this.GetUserVal = 0;
    this.SetUserVal = 1;
}

__topcore.prototype = {
getUserProp: function(sNameCtr, sKey, pFunc) {
    this._doUserCallBack(topcore.GetUserVal, sNameCtr, sKey, null, new topcore.UserPropArgs(sNameCtr, sKey, pFunc));
},

setUserProp: function(sNameCtr, sKey, sVal, pFunc) {
    this._doUserCallBack(topcore.SetUserVal, sNameCtr, sKey, sVal, new topcore.UserPropArgs(sNameCtr, sKey, pFunc));
},

_doUserCallBack: function(iType, sNameCtr, sKey, sVal, pFunc) {
    if (top && top.xmlhttp)
    {
        var sPack = iType + COL_DELIMITER + sNameCtr + COL_DELIMITER + sKey + COL_DELIMITER + sVal;
        top.xmlhttp.doCallBack('__Page',sPack,topcore._callBackSuccess,pFunc,topcore._callBackFail,null,true,null,0);
    }
    else
        alert('Client Personalization not enabled');
},

_callBackSuccess: function (result, ctx, req) {
    if (ctx.pFunc)
        ctx.pFunc(ctx.namingCtr, ctx.key, result);
},

_callBackFail: function (result, ctx) {
	window.status = result;
}
}

__topcore.prototype.UserPropArgs = function(sNameCtr, sKey, pFunc)
{
    this.namingCtr = sNameCtr;
	this.key = sKey;
	this.pFunc = pFunc;
}

var topcore = new __topcore();



//jq

jQuery(function($) {
    $(".i-tabs").each(function() {
        var tabs = $(this);
        var c = $(".i-tabs-container", tabs);
        var event = tabs.attr("event") || 'mouseover'; //mouse over
        var items = $(".i-tabs-item", this);
        items.each(function(i, v) {
            var item = $(this);
            if (i == 0) item.addClass("i-tabs-item-active");
            var content = null;
            var anchor = null;
            var mid = item.attr("mid");
            var eid = item.attr("eid");
            if (!!mid) {
                anchor = $('a[name=' + mid + ']');
                if (anchor.size() == 1) {
                    content = anchor.next();
                    c.append(anchor.hide())
                }
            } else if (!!eid) {
                content = $('#' + eid);
            }
            if (content == null) return;
            c.append(content.addClass("i-tabs-content"));
            if (i > 0) content.hide();
            item.bind(event, function() {
                items.removeClass("i-tabs-item-active");
                item.addClass("i-tabs-item-active");
                $(".i-tabs-content", tabs).hide();
                $(content).show();
            });
        });
    });

    $(".i-columns").each(function() {
        var columns = $(this);
        var items = $(".i-columns-item", this);
        items.each(function(i, v) {
            var item = $(this);
            var mid = item.attr("mid");
            var anchor = $('a[name=' + mid + ']');
            if (anchor.size() != 1) return;
            var content = anchor.next();
            item.append(anchor).append(content);
        });
    });

    $(".i-news").each(function() {
        var news = $(this);
        var pagesize = parseInt(news.attr("pagesize")) || 3;
        var pageindex = 1;
        var effect = news.attr("effect") || "show"; //fade
        var event = news.attr("event") || 'click'; //mouse over
        var auto = news.attr("auto") == "false" ? false : true;
        var timeout = parseInt(news.attr("timeout")) || 3;

        var hideselector = news.attr("hs") || ".i-news-item";

        var newsitems = $(".i-news-item", news);

        var total = newsitems.size();

        var pager = $(".i-news-page", news);

        var pagerPre = $(".i-news-page-pre", news);

        var pagerNext = $(".i-news-page-next", news);

        var pagecount = Math.ceil(total / pagesize);

        var itemcontainer = $('.i-news-item-container', news);

        var pagecontainer = $('.i-news-page-container', news);

        if (itemcontainer.size() == 1) {
            itemcontainer.append(newsitems);
        }
        if (pagecontainer.size() == 1) {
            pagecontainer.append($('.i-news-page-pre,.i-news-page,.i-news-page-next', news));
        }
        newsitems.filter(":odd").addClass("i-news-item-alt");
        pager.filter(":odd").addClass("i-news-page-alt");
        var showNews = function() {
            if (pageindex == 1)
                pagerPre.addClass("i-news-page-pre-disable");
            else
                pagerPre.removeClass("i-news-page-pre-disable");

            if (pageindex == pagecount)
                pagerNext.addClass("i-news-page-next-disable");
            else
                pagerNext.removeClass("i-news-page-next-disable");

            pager.removeClass("i-news-page-active");
            pager.eq(pageindex - 1).addClass("i-news-page-active");

            var l = (pageindex - 1) * pagesize;
            var u = l + pagesize;
            newsitems.each(function(i, v) {
                if (i >= l && i < u) {
                    if (effect == "show") {
                        $(this).show();
                    } else {
                        $(this).fadeIn();
                    }
                    $(this).addClass("i-news-item-active");
                } else {
                    $(this).hide();
                    $(this).removeClass("i-news-item-active");
                }
            });
        };

        pagerPre.bind(event, function() {
            if (pageindex > 1) {
                pageindex--;
                showNews();
            }

        });
        pagerNext.bind(event, function() {
            if (pageindex < pagecount) {
                pageindex++;
                showNews();
            }
        });
        pager.bind(event, function() {
            pageindex = parseInt($(this).attr("page"));
            if (!pageindex) {
                pageindex = $.inArray(this, pager.get()) + 1;
            }
            showNews();
        });
        var __autoPlay = function() {
            pageindex++;
            if (pageindex > pagecount) pageindex = 1;
            showNews();

        };

        var autoPlay = null;

        if (auto) {
            autoPlay = setInterval(__autoPlay, 1000 * timeout);
        }
        $('.i-news-item,.i-news-page,.i-news-page-pre,.i-news-page-next', news).hover(function() {
            if (autoPlay) clearInterval(autoPlay);
        }, function() {
            if (auto) autoPlay = setInterval(__autoPlay, 1000 * timeout);
        });
        showNews();
    });



});