// -----------------------
// General
// -----------------------

function PageName()
{
	var fullpath = window.location.pathname;
	pos = fullpath.lastIndexOf('/');
	if (pos == fullpath.length - 1)
		return "?";
	else if (pos < 0)
		return fullpath;
	else
		return fullpath.substr(pos + 1);
}

function StringToIntArray(str)
{
    var sarr = str.split(',');
    var i;
    var ret = [];
    for (i = 0; i < sarr.length; i++)
        ret[i] = parseInt(sarr[i]);
    return ret;
}

// -----------------------
// Startup
// -----------------------

var startupFunctions = [];
window.onload = ExecStartupFunctions;

function ExecStartupFunctions()
{
    var i;
    for (i = 0; i < startupFunctions.length; i++)
        eval(startupFunctions[i]);
}

function AddStartupFunction(func)
{
    startupFunctions.push(func);
}

// -----------------------
// Sidebar
// -----------------------

function Sidebar_HideShopForLoan()
{
	var obj = document.getElementById('shop-home-loan');
	if (obj)
		obj.style.display='none';
}

// -----------------------
// Cookies
// -----------------------

function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) 
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

// -----------------------
// Login Options
// -----------------------

AddStartupFunction("SetupLoginOptions()");

function SetupLoginOptions()
{
	var obj = document.getElementById('LoginOptions');
	if (obj != null)
	{
		var name = readCookie('LoginName');
		if (name != null)
		{
			obj.innerHTML = name + ": <a href='/ext/users/ViewAccount.aspx' style='color:white'>View Account</a> | <a href='/Ext/UserLogout.aspx' style='color:white'>Sign Out</a>";
		}
	}
}

// -----------------------
// Expandable Topics
// -----------------------

AddStartupFunction("ArticleLists_OnLoad()");

var topicsCookieName;
var topicsState;
var topicIdPrefix = 'Topic_';

function HandleExpandableTopicClick(element)
{
    if (element.className=='expandedtopic')
    {
        element.className = 'collapsedtopic';
        id = parseInt(element.id.substr(topicIdPrefix.length));
        topicsState[id] = 0;
    }
    else if (element.className == 'collapsedtopic')
    {
        element.className='expandedtopic';
        id = parseInt(element.id.substr(6));
        topicsState[id] = 1;
    }
    createCookie(topicsCookieName, topicsState, 3);
}

function AssignIDsToTopics()
{
    var list = document.getElementsByTagName('li');
    var i;
    var id = 0;
    for (i = 0; i < list.length; i++)
    {
        if (list[i].className == 'expandedtopic' || list[i].className == 'collapsedtopic')
        {
            list[i].id=topicIdPrefix + id;
            id++;
        }
    }

    cookie = readCookie(topicsCookieName);
    if (cookie == null)
    {
        topicsState = [];
        for (i = 0; i < id; i++)
            topicsState[i] = 0;
    }
    else
    {
        topicsState = StringToIntArray(cookie);
        if (topicsState.length > id)
            topicsState.length = id;
    }
    createCookie(topicsCookieName, topicsState, 3);
}

function SetTopicState(list)
{
    var i = 0;
    var done = false;
    var element;
    
    do
    {
        element = document.getElementById(topicIdPrefix + i);
        if (element)
        {
            if (topicsState[i] == 0)
                element.className = 'collapsedtopic';
            else
                element.className = 'expandedtopic';
        }
        else
        {
            done = true;
        }
        i++;
    } while (!done);
}

function ArticleLists_OnLoad()
{
    topicsCookieName = topicIdPrefix + PageName();
    AssignIDsToTopics();
    SetTopicState();
}


// ------------------------------------
// Qualification Sensitivity Section
// ------------------------------------

var currentOpenedQualSection = null;
var currentHighlightedCells = null;
var currentHighlightedClass = null;
 
function ToggleQualSection(sectionId, cellList, highlightClass, bground)
{
	if (currentOpenedQualSection != sectionId)
	{
		CloseQualSection();
		$('#'+sectionId).slideDown();
		currentOpenedQualSection = sectionId;

		if (cellList != undefined)
		{
			var cells = cellList.split(",");
			var alength = cells.length;
			for (i = 0;  i < alength; i++)
			{
				$("td[id='"+cells[i]+"']").addClass(highlightClass);

				var cell = document.getElementById(cells[i]);
				if (highlightClass == 'LostQualificationCell' && cell.innerHTML == '')
					cell.innerHTML = "Don't Qualify";
				if (highlightClass == 'GainQualificationCell' && cell.innerHTML.substring(0,5) != "Could")
					cell.innerHTML = "Could " + cell.innerHTML;

				var markerId = "MarkerImage" + (i + 1);
				var marker = document.getElementById(markerId);
				marker.src = "/images/icons/QualMarker" + (i + 1) + ".png";
				marker.style.backgroundColor = bground;
				marker.style.display = "block";
				
				var leftOffset = 0;
				leftOffset = $(cell).offset().left;
				if (i > 0 && (cells[i-1] == cells[i]))
				{
					leftOffset = leftOffset + cell.offsetWidth - marker.offsetWidth;
				}
				$(marker).offset({ top: $(cell).offset().top, left: leftOffset });
				//marker.style.left = leftOffset + "px";
				//marker.style.top = GetTop(cell) + "px";
				
			}
			currentHighlightedCells = cells;
			currentHighlightedClass = highlightClass;
		}
	}
	else
		CloseQualSection();
}

function CloseQualSection()
{
	if (currentOpenedQualSection !=  null)
	{
		$('#'+currentOpenedQualSection).slideUp();
		currentOpenedQualSection = null;
	}

	if (currentHighlightedCells != null)
	{
        var alength = currentHighlightedCells.length;
		for (i = 0; i < alength; i++)
		{
			$("td[id='" + currentHighlightedCells[i] + "']").removeClass(currentHighlightedClass);
			$("#MarkerImage" + (i + 1)).css("display", "none");
			var cell = document.getElementById(currentHighlightedCells[i]);
			if (cell != null && cell.innerHTML.substring(0,5) == "Don't")
				cell.innerHTML = '';
			if (cell != null && cell.innerHTML.substring(0,5) == "Could")
				cell.innerHTML = cell.innerHTML.substring(6);
		}
		currentHighlightedCells = null;
		currentHighlghtedClass = null;
	}
}


// -----------------------
// Calculator IFrames
// -----------------------

function ResizeIframeByRef(frm)
{
    try
    {
        // Find the height/width of the internal page
		var theHeight;
		var theWidth;
		if (frm)
		{
		        var theHeight = frm.contentWindow.document.body.scrollHeight;
	        	var theWidth = frm.contentWindow.document.body.scrollWidth;
	
		        // Resize the iframe
	        	frm.style.height = (theHeight+20) + "px";  // 20px is added to ensure a vertical scroll bar doesn't appear for IE7 and IE8
		        frm.style.width = (theWidth) + "px";
		}
    }
    catch(e)
    {
    }
}

// -----------------------
// Printing
// -----------------------

function PrintPage()
{
    window.open(location.href + "?print", "", "status=1, scrollbars=1");
}

// -----------------------
// ScrollToElement
// -----------------------

function ScrollToElement(theElementName)
{
  var selectedPosX = 0;
  var selectedPosY = 0;
  var theElement = document.getElementById(theElementName);
              
  if (theElement != null)
  {
	  while(theElement != null)
	  {
	    selectedPosX += theElement.offsetLeft;
	    selectedPosY += theElement.offsetTop;
	    theElement = theElement.offsetParent;
	  }
 	  window.scrollTo(selectedPosX,selectedPosY);
  }
}

// -----------------------
// Google Search
// -----------------------

function SiteSearch()
{
	window.location='http://www.google.com/search?sitesearch=' + 'www.mtgprofessor.com' + '&as_q=' + document.getElementById('search-field').value
}

// -----------------------
// Handle a key press in the Search Textbox
// -----------------------

function HandleSearchKeyPress(e)
{
    var ENTER_KEY = 13;
    var code = "";
          
    if (window.event) // IE
    {
        code = e.keyCode;
    }
    if (e.which) // Netscape/Firefox/Opera
    {
        code = e.which;
    }

    if (code == ENTER_KEY) 
    {
        document.getElementById("SearchButton").onclick();
        return false;
    }
}

// -----------------------
// Mouse-Over Hints
// -----------------------


var currentOpenHintName = null;

function HideHint(divPopUpName)
{
    var divPopUp = document.getElementById(divPopUpName)
    if (divPopUp == null)
        return;
    divPopUp.style.display = "none";
    currentOpenHintName = null;
}

function ShowHint(divPopUpName, lnk)
{
    var divPopUp = document.getElementById(divPopUpName)
    if (divPopUp == null)
        return;
        
    if (currentOpenHintName != null)
    	HideHint(currentOpenHintName);
    	
    divPopUp.style.display = "block";     //must make visible BEFORE positioning
    divPopUp.style.position = "absolute";
    var x = (GetLeft(lnk) + lnk.offsetWidth + 10);
    var y = GetTop(lnk);
    
    var vy = GetPageScrollY(); 
    var vx = GetPageScrollX();
    var ph = GetPageHeight();
    
    var clientHeight = GetClientHeight();
    var clientWidth = GetClientWidth();
    var divHeight = divPopUp.offsetHeight;
    var divWidth = divPopUp.offsetWidth;
    var divTop = y;
    
    var bottomLoss = divHeight + divTop - clientHeight - vy + 17;
    if(bottomLoss > 0)
    {
        y -= bottomLoss;
    }
    
    var rightLoss = divWidth + x - clientWidth - vx + 17;
    if (rightLoss > 0)
    {
    	x = GetLeft(lnk) - divWidth - 17;
    }
    
//    divPopUp.style.top  = y + "px";
//    divPopUp.style.left = x + "px";
	$(divPopUp).offset({ top: y, left: x });
	currentOpenHintName = divPopUpName; 
}

function SetMenuOptionsRight(divPopUp, lnk)
{
    divPopUp.style.display = "";     //must make visible BEFORE positioning
    divPopUp.style.position = "absolute";
    var x = (GetLeft(lnk) + lnk.offsetWidth + 0);
	var newx  = (GetLeft(lnk)  -  (divPopUp.offsetWidth + 5) );
    var y = GetTop(lnk);
    
    var vy = GetPageScrollY(); 
    var ph = GetPageHeight();
    
    var clientHeight = GetClientHeight();
    var divHeight = divPopUp.offsetHeight;
    var divTop = y;

    if( (divHeight+divTop) > (clientHeight + vy))
    {
        y -= (divHeight-lnk.offsetHeight);
    }
    divPopUp.style.top  = y + "px";
    divPopUp.style.left = newx + "px";
}

function GetPageHeight() 
{
	var browserHeight = GetClientHeight();
	if (document.clientHeight && docment.clientHeight != 0 && document.clientHeight != browserHeight) 
		return document.clientHeight;
	else if (document.body && document.body.clientHeight && document.body.clientHeight != 0 && document.body.clientHeight != browserHeight)
		return document.body.clientHeight;
	else if (document.body && document.body.scrollHeight && document.body.scrollHeight != 0 && document.body.scrollHeight != browserHeight)
		return document.body.scrollHeight;	
	return 0;
}    

function GetPageWidth() 
{
	var browserWidth = GetClientWidth();
	if (document.clientWidth && docment.clientWidth != 0 && document.clientWidth != browserWidth) 
		return document.clientWidth;
	else if (document.body && document.body.clientWidth && document.body.clientWidth != 0 && document.body.clientWidth != browserWidth)
		return document.body.clientWidth;
	else if (document.body && document.body.scrollWidth && document.body.scrollWidth != 0 && document.body.scrollWidth != browserWidth)
		return document.body.scrollWidth;	
	return 0;
}

// Returns the Top position of an object, relative to the page.
// Remarks: Object must be displaying to return a position.
function GetTop(obj) 
{
   var nPos = new Number(0);
   var oCurrent;  

   oCurrent = obj;
   while (oCurrent) 
   {
      nPos += oCurrent.offsetTop;
      oCurrent = oCurrent.offsetParent;
   }
   
   return nPos;
}

// Returns the Left position of an object, relative to the page.
// Remarks: Object must be displaying to return a position.
function GetLeft(obj) 
{
   var nPos = new Number(0);
   var oCurrent;

   oCurrent = obj;
   while (oCurrent) 
   {
      nPos += oCurrent.offsetLeft;
      oCurrent = oCurrent.offsetParent;
   } 
   return nPos;
}

function GetClientHeight() 
{
    if (window.innerWidth && window.innerHeight) 
    {
        return window.innerHeight;
    }
    else if (document.compatMode=='CSS1Compat' &&
        document.documentElement &&
        document.documentElement.offsetWidth ) 
    {
        return document.documentElement.offsetHeight;
    }
    else if (document.body && document.body.offsetWidth) 
    {
        return document.body.offsetHeight;
    }
   return 0;
}

function GetClientWidth() 
{
    if (window.innerWidth && window.innerHeight) 
    {
        return window.innerWidth;
    }
    else if (document.compatMode=='CSS1Compat' &&
        document.documentElement &&
        document.documentElement.offsetWidth ) 
    {
        return document.documentElement.offsetWidth;
    }
    else if (document.body && document.body.offsetWidth) 
    {
        return document.body.offsetWidth;
    }
    return 0;
}

function GetPageScrollY() 
{
    if ((document.documentElement != undefined) && (document.documentElement.scrollTop != undefined)) 
    {
        return document.documentElement.scrollTop;
    }
    else if (window.pageYOffset != undefined) 
    {
        return window.pageYOffset;
    } 
    else if (document.body.scrollTop != undefined) 
    {
        return document.body.scrollTop;
    } 

    return null;
}

function GetPageScrollX() 
{
    if ((document.documentElement != undefined) && (document.documentElement.scrolllLeft != undefined)) 
    {
        return document.documentElement.scrollLeft;
    }
    else if (window.pageXOffset != undefined) 
    {
        return window.pageXOffset;
    } 
    else if (document.body.scrollLeft != undefined) 
    {
        return document.body.scrollLeft;
    } 

    return null;
}

// -----------------------
// Modal Pop-Ups
// -----------------------
function ShowModalPopup(elementName)
{
    var divPopup = document.getElementById(elementName);
    if (divPopup)
    {
		divPopup.style.display = 'block';
	    var divHeight = divPopup.offsetHeight;		
	    var vy = GetPageScrollY(); 
	    var clientHeight = GetClientHeight();
	    var y = vy + (clientHeight - divHeight) / 2;
    
	    var divWidth = divPopup.offsetWidth;
	    var vx = GetPageScrollX();
	    var clientWidth = GetClientWidth();
	    var x = vx + (clientWidth - divWidth) / 2; 
	    
	    divPopup.style.top = y + 'px';
	    divPopup.style.left = x + 'px';
	    
	    DisablePage();
    }
}

function CloseModalPopup(elementName)
{
    var divPopup = document.getElementById(elementName);
    if (divPopup)
    {
    	divPopup.style.display='none';
    	EnablePage();
	}	
}

function DisablePage()
{
	var divtemp;
	divtemp = document.createElement("div");
	divtemp.style.top = 0;
	divtemp.style.left = 0;

	divtemp.style.height = GetPageHeight() + "px";
	//divtemp.style.width = GetPageWidth() + "px";
	divtemp.style.width = "1042px";

	divtemp.id = "CoverDiv";
	divtemp.className = 'disablePage';
	var arrForm = document.getElementsByTagName("Form");
	arrForm[0].appendChild(divtemp)
	
	//document.getElementById("divtemp").appendChild("floatlayer");
}

function EnablePage()
{
	var coverElement = document.getElementById('CoverDiv');
	if (coverElement)
	{
		var arrForm = document.getElementsByTagName("Form");
		arrForm[0].removeChild(coverElement);
	}
}
 
// -----------------------
// Pop-Ups
// -----------------------

var currentPopUpName = null;

function ShowPopUp(divPopUpName, lnk)
{
    CloseCurrentPopUp();
        
    ShowHint(divPopUpName, lnk);
    currentPopUpName = divPopUpName;    
}

function CloseCurrentPopUp()
{
    if (currentPopUpName != null)
    {
        HideHint(currentPopUpName);
        currentPopUpName = null;
    }
}

function PrintCurrentPopUp()
{
    var currentPopUp = document.getElementById(currentPopUpName);
    var w =  window.open();
    var bdy = '<head><link rel="stylesheet" href="/styles/style.css" type="text/css" media="screen" /><link rel="stylesheet" href="/styles/style.css" type="text/css" media="print" /></head><body>' + currentPopUp.innerHTML + "</body>";
    bdy = bdy.replace(">Print<", "><").replace(">Close", ">").replace(">X<", "><");
    w.document.write(bdy);
    w.document.close();
    w.print();
}


// -----------------------
// Details Pop-Ups
// -----------------------

var currentHighlightedDetails = null;


function ShowDetailsPopUp(divPopUpName, lnk)
{
	HighlightDetailsImage(lnk);
    ShowPopUp(divPopUpName, lnk);
}

function HighlightDetailsImage(lnk)
{
	UnhighlightCurrentDetailsImage();
	
	var obj = lnk;
	while (obj != null && obj.nodeName != 'TD')
		obj = obj.parentNode;
	if (obj != null)
	{
		obj.className = ' HighlightedCell';
	    currentHighlightedDetails = obj;
	}
}

function UnhighlightCurrentDetailsImage()
{
	if (currentHighlightedDetails != null)
	{
		currentHighlightedDetails.className = '';
	    currentHighlightedDetails = null;
    }
}

function CloseCurrentDetailsPopUp()
{
    CloseCurrentPopUp();
    UnhighlightCurrentDetailsImage();
}

// -----------------------
// Query String
// -----------------------

function getQueryParameterByName(name) 
{ 
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); 
  var regexS = "[\\?&]" + name + "=([^&#]*)"; 
  var regex = new RegExp(regexS); 
  var results = regex.exec(window.location.href); 
  if(results == null) 
    return ""; 
  else 
    return decodeURIComponent(results[1].replace(/\+/g, " ")); 
} 

// -----------------------
// Google Analytics
// -----------------------
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-20058603-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    //alert(document.location.hostname);
  	if (document.location.hostname.indexOf('mtgprofessor.com') >= 0)
  	{
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    }
  })();

