// JScript File

/*
	Locates a document object of the provided id and returns the object
	layers, document.all and getElementById compatible
*/
function getObject(objIdentifier)
{
	var myObj = null;

	if (document.layers) {
	    myObj = eval("document." + objIdentifier);
	    if (!myObj) {
	        for (var index = 0; index < document.layers.length; index++) {
	            if (eval("document." + document.layers[index].id) && eval("document." + document.layers[index].id + ".document." + objIdentifier)) {
	                myObj = eval("document." + document.layers[index].id + ".document." + objIdentifier);
	                break;
	            }
	        }
	    }
	}

	else if (document.getElementById) {
	    myObj = eval("document.getElementById('" + objIdentifier + "')");
	}
	else {
	    myObj = eval("document.all['" + objIdentifier + "']");
	}

	return myObj;           
}

//function error(error) {
//    alert("JScript Error in util.js: " + error);
//}

function removeInvalidCharacters(keywords) {
    return keywords.replace(/[^\w\s\-']/gi, "");
}

function show(id)
{
    var elem = getObject(id);
    if (elem) {
        elem.style.display = "block";
    }
    else {
        error("Invalid ID passed to show(). Invalid ID: " + id);
    }
}

function hide(id)
{
    var elem = getObject(id);
    if (elem) {
        elem.style.display = "none";
    }
    else {
        error("Invalid ID passed to hide(). Invalid ID: " + id);
    }
}


function showElem(elem)
{
    if (elem) {
        elem.style.display = "block";
    }
    else {
        error("Invalid Element passed to showElem()");
    }
}
 

function hideElem(elem)
{
    if (elem) {
        elem.style.display = "none";
    }
    else {
        error("Invalid Element passed to hideElem()");
    }
}

function toggle(id)
{
    var elem = getObject(id);
    if (elem) {
        if (elem.style.display == "none") {
            elem.style.display = "block";
        }
        else {
            elem.style.display = "none";
        }
    }
    else {
        error("Invalid ID passed to toggle(). Invalid ID: " + id);
    }
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
  window.onload = function() {
      oldonload();
      func();
  };
  }
}

function setCookie(name, value, expires, path, domain, secure) { 
	var curCookie = name + "=" + escape(value) + 
		((expires) ? "; expires=" + expires.toGMTString() : "") + 
		((path) ? "; path=" + path : "") + 
		((domain) ? "; domain=" + domain : "") + 
		((secure) ? "; secure" : ""); 
	document.cookie = curCookie;
}

function contentSearch (keywords) {
    if (keywords.length > 0) {
        window.location.href = "/search/" + removeInvalidCharacters(keywords);
    }
    else {
        alert('You must enter a search string.');
    }
}


function categoryRedirect (categoryAlias) {
    domain = window.location.href.match(/(http:\/\/)([^\/]*).*/);

    if (categoryAlias.length) {
        window.location.href = domain[1] + domain[2] + categoryAlias;
    }
    else {
        alert('Please select a team!');
    }
}

function getKeyCode(e) {
    var characterCode;

    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which;  //character code is contained in NN4's which property
    }
    else {
        e = event;
        characterCode = e.keyCode;  //character code is contained in IE's keyCode property
    }

    return characterCode;
}

function submitSearchFromEnter (e, keywords) {
	if (getKeyCode(e) == 13 && keywords !== '')
    {
        contentSearch(keywords);
        return false;
    }

    return true;
}

//JAG 4/25/2007 Added 
function FindElementByPartialName(partialName, tagType)
{
	var found = "false";
	var elementname = "not found";
	
//    for(i=0; i<document.forms[0].elements.length; i++){
//		elementname = document.forms[0].elements[i].id;
//		
//		if(elementname.indexOf(partialName) > 0 )
//		{
//			
//			found = "true";
//			break;
//		}
//	}

//	if(found == "true")
//	{
//		return elementname;
//	}
//	else
//	{
	var tags = document.forms[0].getElementsByTagName(tagType);

		for(i=0; i<tags.length; i++)
		{
			var t = tags[i];
			
			if(t.id !== "")
			{
				var tid = t.id;
				if(tid.indexOf(partialName) >= 0 )
				{
					elementname = tid;
				}
			}
		}
//	}
	
	return elementname;
}

function isNumberKey(evt) {
    // var character = evt.which;
    if (typeof (event) != 'undefined') {
        var character = evt.which ? evt.which : event.keyCode;
    }
    else {
        var character = evt.which;
    }
    // Allowed Character Key Codes
    // 0, 8, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57
    // build an array of accepted codes
    var allowedCharCodes = [0, 8, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
    // Check if our character input is in said array
    var charCheck = jQuery.inArray(character, allowedCharCodes)
    // if the character code is not in the array, inArray returns -1.
    if (charCheck > -1) {
        // alert('digit!');
        return true;
    }
    else {
        if (typeof (event) != 'undefined') {
            if (typeof (event.preventDefault) != 'undefined') {
                event.preventDefault();
            }
        }
        else {
            if (typeof (evt.preventDefault) != 'undefined') {
                evt.preventDefault();
            }
        }
        return false;
    }
}


//JAG 5/2/2007 Added for the enterkey press to fire the sweepstake entry on superpartner sites
function doSweepsEnter(e, id, buttonid)
{
	if (getKeyCode(e) == 13)
	{
		var tbo = document.getElementById(id);
		if(tbo.value !== "Enter Email Address" && tbo.value !== null)
		{
			var button = document.getElementById(buttonid);
			WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(buttonid, '', true, 'sweepsEntry', '', false, false));
			//button.click();
		}
	}
}

  /**
 * JAG 5/15/2007 Added to find the coordinates of an element on the view cart page
 * Retrieve the absolute coordinates of an element.
 *
 * @param element
 *   A DOM element.
 * @return
 *   A hash containing keys 'x' and 'y'.
 */
function getAbsolutePosition(element) {
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}
/*
 * MH 10/10/2007 Added to find the X and Y coordinates 
 */
 function PositionMe(target, source, offsetY, offsetX)
{
    target = document.getElementById(target);
    source = document.getElementById(source);
    target.style.top = findPosY(source) - offsetY;
    target.style.left = findPosX(source) - offsetX;
} 


function formatCurrency(num) {
    num = num.toString().replace(/$|,/g, '');

    if (isNaN(num)) {
        num = "0";
    }

    var sign = (parseInt(num, 10) === parseInt(Math.abs(num),10));
    num = Math.floor(num * 100 + 0.50000000001);
    var 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);
}


/*
AG: This function is used to hide the certain block of text wrapped in a div and it also flip the button image + to - 
*/
function flipDivWithToggleImage(divArea, imgSrcID) {
    var sImage = getObject(imgSrcID);
    
    if (sImage.src == 'http://images.footballfanatics.com/FF_deletebutton_100108.gif') {
        sImage.src = 'http://images.footballfanatics.com/FF_addbutton_100108.gif';
        hide(divArea);
    }
    else {
        sImage.src = 'http://images.footballfanatics.com/FF_deletebutton_100108.gif';
        show(divArea);
    }

    return false;
}


function removeSpaces(tbxToCheckId)
{
    var tbx = document.getElementById(tbxToCheckId);
    tbx.value = tbx.value.replace(' ','');
}


function toggleTargetDisplay(target) {
    jQuery('div#' + target).toggleClass('display');
}

function emailSignup(emailInputId, favTeamSelectId, submit) {

    var emailinput = jQuery("#" + emailInputId);
    var teamselect = jQuery("#" + favTeamSelectId);
    var url = "";
    
    if (teamselect.length > 0)
        url = "/Services/EmailSignup.ashx?email=" + emailinput.val() + "&team=" + teamselect.val() + "&teamname=" + jQuery("#" + favTeamSelectId + " option:selected").text();
    else
        url = "/Services/EmailSignup.ashx?email=" + emailinput.val() + "&singleteam=true";
    
    // disable submit button
    jQuery(submit).attr("disabled", "disabled");
    jQuery.getJSON(url, function(json) {
        alert(json.ErrorMessage);
        if (json.Result == true) {
            emailinput.val('');
            teamselect.val('');
        } else {
            if (json.ErrorSource == "email")
                emailinput.focus();
            else
                teamselect.focus();
        }
        // reenable submit button
        jQuery(submit).removeAttr("disabled");
    });
}
