///<reference path="../df/df.js" />
//global Comcast namespace
window.Comcast = window.Comcast || {};


// * Returns the namespace specified and creates it if it doesn't exist
// *
// * Comcast.namespace("property.package");
// * Comcast.namespace("Comcast.property.package");
// *
// * Either of the above would create DF.property, then
// * Comcast.property.package
// *
// * Note: No reserved words as the property or package names!
// *
// * @param  {String} ns The name of the namespace
// * @return {Object} A reference to the namespace object
Comcast.namespace = function(ns) {

    if (!ns || !ns.length) {    
        return null;
    }

    var levels = ns.split(".");
    var nsobj = Comcast;

    // ignore 'DF' on front, since it's already specified
    for (var i=(levels[0] == "Comcast") ? 1 : 0; i<levels.length; ++i) {
        nsobj[levels[i]] = nsobj[levels[i]] || {};
        nsobj = nsobj[levels[i]];
    }

    return nsobj;
};

//******************** Forms **********************/
Comcast.namespace('Comcast.Ui');
Comcast.namespace('Comcast.Ui.Forms');
Comcast.namespace('Comcast.Validation');
(function() {
	
	// * Updates the fields of a form to allow and clear defau
	// * text
	// *
	// * Comcast.Ui.Forms.InitFormFields();
	// * Comcast.Ui.Forms.InitFormFields(rootElement);
	// *
	// * Either of the above would create would rip through the
	// * elements under either the rootElement or document and
	// * set the text fields to default content
	// *
	// *
	// * @param  {Element} rootElement the element to start DOM walking from
	Comcast.Ui.Forms.InitFormFields = function(rootElement)
	{
	    
		var clearField = function()
		{
		    var defaultText = this.getAttribute("defaultValue");
			var valueMaxLength = this.getAttribute("valueMaxLength");
			if(defaultText == "Password" && this.type == "text")
			{	
				try
				{
					var type = this.getAttributeNode("type");
					type.nodeValue = "password";
					this.value = "";
					this.focus();
				}
				catch (e)
				{
					var newInput = document.createElement("input");
					newInput.type = "password";
					newInput.id = "password"
					newInput.setAttribute("defaultValue",defaultText);
					newInput.name = "password";
					newInput.className = "textBox";
					newInput.onfocus = clearField;
					newInput.onblur = defaultField;
					newInput.value = "";
					newInput.style.width = "101px";
					this.replaceNode(newInput);
					newInput.focus();
					newInput.focus(); // needs double focus for some reason
				}
			}
			
			if(this.value.trim() == defaultText)
			{
				this.value = "";
				if(!isNullOrEmpty(valueMaxLength))
				{
				    this.maxLength = valueMaxLength;
				}
			}
		}

		var defaultField = function()
		{
		    var defaultText = this.getAttribute("defaultValue");
			if(defaultText == "Password")
			{
				try
				{
					if(this.value.trim() == "")
					{
						this.type = "text";
					}
				}
				catch (e)
				{
					var newInput = document.createElement("input");
					newInput.type = "text";
					newInput.id = "password"
					newInput.name = "password";
					newInput.className = "textBox";
					newInput.style.width = "101px";
					newInput.setAttribute("defaultValue",defaultText);
					newInput.onblur = defaultField;
					newInput.onfocus = clearField;
					newInput.value = defaultText;
					this.replaceNode(newInput);
					return;
				}
			}
			if(this.value.trim() == "")
			{
				this.maxLength = 200;
				this.value = defaultText;
			}
		}
		
		var clearDefaultFields = function(evt)
		{
		    evt = (evt) ? evt : ((window.event) ? window.event : null);
			var form = (evt.currentTarget) ? evt.currentTarget: evt.srcElement;
			var input = form.getElementsByTagName("input");
			
			for(var i = 0;i < input.length;i++)
			{
				if ( input[i].type == "text" )
				{
					var defaultText = input[i].getAttribute("defaultValue");
					if(input[i].value == defaultText)
					{
						input[i].value = "";
					}
				}
			}
		}
		var rootElement = rootElement == null ? document : rootElement;
		var input = rootElement.getElementsByTagName("input");
		for(var i = 0;i < input.length;i++)
		{
			if ( input[i].type == "text" )
			{	
				var defaultText = input[i].getAttribute("defaultValue");
				if(input[i].value.trim() == "")
				{
					input[i].value = defaultText;
					//input[i].maxLength = "";
				}
				//input[i].onfocus = clearField;
				//input[i].onblur = defaultField;
				DF.evt.Event.addListener(input[i], "focus", clearField.createDelegate(input[i]));
				DF.evt.Event.addListener(input[i], "blur", defaultField.createDelegate(input[i]))
				
			}
		}
		
		var formList = rootElement.getElementsByTagName("form");
		for(var i = 0;i < formList.length;i++)
		{
			DF.evt.Event.addListener(formList[i], "submit", clearDefaultFields);
		}
		
	}
	
	// * Sets up button roll over states
	// *
	// * Comcast.Ui.Forms.InitButtons();
	// * Comcast.Ui.Forms.InitButtons(rootElement);
	// *
	// * Either of the above would create would rip through the
	// * elements under either the rootElement or document and
	// * set images with class 'button' or inputs of type image
	// * to have roll-over states
	// *
	// * @param  {Element} rootElement the element to start DOM walking from
	Comcast.Ui.Forms.InitButtons = function (rootElement) {
	    rootElement = rootElement == null ? document : rootElement;
		var aImg = rootElement.getElementsByTagName("img");
		for (var i = 0; i < aImg.length; i++)
		{
			if(DF.Dom.hasClass(aImg[i], "button") && aImg[i].getAttribute("rolloverSet") != "yes")
			{
				DF.evt.Event.addListener(aImg[i], "mouseover", Comcast.Ui.buttonRollOn.createDelegate(aImg[i]));
				DF.evt.Event.addListener(aImg[i], "mouseout", Comcast.Ui.buttonRollOff.createDelegate(aImg[i]));
				aImg[i].setAttribute("rolloverSet", "yes");
				
				if (DF.Dom.hasClass(document.body, "debugRollovers"))
				    aImg[i].style.border = "1px solid blue";
			}
		}
		
		var inputButtons = rootElement.getElementsByTagName("input")
		for (var i = 0; i < inputButtons.length; i++)
		{
			if(inputButtons[i].type == "image" && inputButtons[i].getAttribute("rolloverSet") != "yes")
			{
				DF.evt.Event.addListener(inputButtons[i], "mouseover", Comcast.Ui.buttonRollOn.createDelegate(inputButtons[i]));
				DF.evt.Event.addListener(inputButtons[i], "mouseout", Comcast.Ui.buttonRollOff.createDelegate(inputButtons[i]));				
				inputButtons[i].setAttribute("rolloverSet", "yes");
				
				if (DF.Dom.hasClass(document.body, "debugRollovers"))
				    inputButtons[i].style.border = "1px solid blue";
			}
		}
	}
	
	Comcast.Ui.buttonRollOn = function() {
	    var sOrgSrc = this.getAttribute("src");
		var sImage = sOrgSrc.substring(sOrgSrc.lastIndexOf("/"),sOrgSrc.length);
		var sExtension = sImage.substring(sImage.indexOf("."), sOrgSrc.length);
		
		// Make sure we're not already in a rollover state
		if (sOrgSrc.match(/_over\./))
			return;
		
		var sNewSrc = sOrgSrc.substring(0, sOrgSrc.lastIndexOf(".")) + "_over" + sExtension;
		this.setAttribute("orgSrc", sOrgSrc);
		this.setAttribute("src", sNewSrc);
	}

	Comcast.Ui.buttonRollOff = function() {
	    var sOrgSrc = this.getAttribute("orgSrc");
		
		// Under some circumstances, when the page is reloaded while the mouse is over the button
		// we can get a mouseout event without a preceeding mouseover. Trying to do the swap in
		// that case will set src to "".
		if (sOrgSrc && sOrgSrc != this.getAttribute("src"))
			this.setAttribute("src",sOrgSrc);
	}
	
	// * Validate a ZIP code field
	// *
	// * Comcast.Validation.ValidateZIP(zField)
	// *
	// * Validate a 5 digit zip code and return either
	// * null string or error message
	// *
	// * @param  {Element} input field to validate
	// * @return {String} error message, null string if no error
	Comcast.Validation.ValidateZIP = function(zfield, focusField) {
	    focusField = isNull(focusField) ? true : focusField;
		var zvalue = zfield.value;
		var message = ""
		var zerocount = 0;
		if (zvalue.length!=5) {
			message = "Please enter a 5-digit ZIP Code.";
			if(focusField == true)
			    zfield.focus();
			return message;
		}
		for (var i=0; i < zvalue.length; i++) {
			temp = "" + zvalue.substring(i, i+1);
			if (temp == "0") zerocount++;
			if (zerocount == 5) {
				message = "Please enter a 5-digit ZIP Code.";
				zfield.select();
				return message;
			}
		}
		var valid = "0123456789"
		var ok = "yes";
		var temp;
		for (var i=0; i < zvalue.length; i++) {
			temp = "" + zvalue.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") ok = "no";
		}
		if (ok == "no") {
			message = "Please enter a 5-digit ZIP Code.";
			if(focusField == true)
			    zfield.focus();
			return message;
		}
	
		return "";
	}
	
	Comcast.Ui.UpdateLocalization = function() {
	    // Update any modules
		if(DF.Modules.ModuleCollection.getLength() > 0)
		{
			DF.Modules.ModuleCollection.refresh(Comcast.Ui.ModuleUpdateComplete.createDelegate());
		}
		// Update localization info
		Comcast.Ui.UpdateLocHeader();
	}
	
	Comcast.Ui.ModuleUpdateComplete = function () {
	    // Update buttons in modules
		for(var i = 0; i < DF.Modules.ModuleCollection.getLength(); i++)
		{
			// Modules are named not ided.  That way the same module can occur on a page more than once.
			// getModuleElement returns an array of the modules with the currect one's name
			var module = DF.Modules.ModuleCollection.getItem(i).getModuleElement()
			for(var x = 0; x < module.length; x++)
			{
				var m = module[x];
				Comcast.Ui.Forms.InitButtons(m);
			}
		}
	}
	
	Comcast.Ui.UpdateLocHeader = function () {
	    var locHeader = DF.$("locationInfo");
        var locHeaderEs = DF.$("locationInfoEs");
        var locCookie = getCookie("Serviceability");
        if(locCookie.length > 0)
        {
			if(DF.Util.Cookies.getCookie("Serviceability","Zip") != false)
			{
				if(window.location.pathname.indexOf("/es/") > 0)
				{
					//This should only be valid for CM
					//the locationInfoEs div does not exist in non-CM pages.
					locHeaderEs.style.display = "block";
					var zipHeader = DF.$("zipInfoEs");
					zipHeader.innerHTML = Comcast.Ui.get5DigitZip();
				}
				else
				{
					locHeader.style.display = "block";
					var zipHeader = DF.$("zipInfo");
					zipHeader.innerHTML = Comcast.Ui.get5DigitZip();
				}
            }
        }
        
        var accountHeader = DF.$("myAccountInfo");
        var accountCookie = getCookie("Session");
        if(!isNullOrEmpty(accountCookie))
        {
			if(DF.Util.Cookies.getCookie("Session","Hash") != false)
				accountHeader.style.display = "block";
			if(GetCookie("Serviceability","Zip") != false)
			    accountHeader.innerHTML += "|&#160;";
        }
	}
	
	Comcast.Ui.get5DigitZip = function()
	{
	    //Substring is done to remove the +4 digit zip code returned from CSG
		var zip = DF.Util.Cookies.getCookie("Serviceability","Zip");
		if(!isNullOrEmpty(zip))
			return zip.substring(0,5);
		return "";
	}
})();
