//******************************MWCookieParser.js uses Cookies.js*************************
function Cookie()
{
	var wellKnownValues = new WellKnownMWCookieValues();
	var value = GetCookie("mymw");
	var mwprtf = GetCookie("marketwatchportfolio");
	
	this._port = mwprtf;
	this._value = value;
	this.load();	
	
	/**
	 ** This function is called externally. It helps format the text which
	 ** populates an HTML text box.
	 **/
	Cookie.ReturnArrayAsString = function(symbolArray)
	{	
		if(symbolArray != null && symbolArray.length > 0)
		{
			return symbolArray.join('|');
		}
		else
		{
			return "";
		}
	};
	
	Cookie.SetMyMwCookieValue = function(cookieValue)
	{
		return SetCookie("mymw", cookieValue);  //SetCookie is from Cookies.js
	};
	
	/**
	 ** Bulds custom section just for news clips.
	 **/
	Cookie.BuildNewsClipSection = function(textValue)
	{
		if(textValue!=null && textValue.length>=32)
		{
			var wellKnownValues = new WellKnownMWCookieValues();
			var returnString = wellKnownValues.GetNewsClipsSectionHeader();
			var newsClipArray = TransformNewsClipStringToArray(textValue);
			returnString += newsClipArray.join('|');
			return returnString;
		}
		else
		{
			return "";
		}
	};
	
	Cookie.GetVersion = function(cookieString)
	{
		if(cookieString.substring(0,2) == "v=")
		{
			if(cookieString.indexOf('&') == -1)
			{
				return cookieString.substring(2);
			}
			else
			{
				return cookieString.substring(2,cookieString.indexOf('&'));
			}
		}
		else if(cookieString.substring(0,8) == "version=")
		{
			if(cookieString.indexOf('&') == -1)
			{
				return cookieString.substring(8);
			}
			else
			{
				return cookieString.substring(8,cookieString.indexOf('&'));
			}
		}
	};
	
	Cookie.GetSection = function(sectionArray,type)
	{
		for(var iCount=0;iCount<sectionArray.length; iCount++)
		{
			var sectionString = sectionArray[iCount];
			if(sectionString.length > type.length)
			{
				var header = sectionString.substring(0,type.length);
				if(header == type)
				{
					return sectionString.substring(type.length);
				}
			}
		}
		return "";
	};
	
	/**
	 ** This function searches for an existing instance of a string within
	 ** an array and will remove it after adding it to the front of the array.
	 **/
	Cookie.BumpArray = function(symbol,symbolArray)
	{
		if ( symbolArray != null )
		{
			symbolArray.unshift(symbol);
			for( var iBumpCounter=1;iBumpCounter<symbolArray.length; iBumpCounter++ )
			{
				var symbolString = symbolArray[iBumpCounter];
				if(symbolString.toUpperCase() == symbol.toUpperCase())
				{
					var aArray = symbolArray.splice(iBumpCounter,(symbolArray.length - iBumpCounter));
					aArray.shift();
					symbolArray = symbolArray.concat(aArray);
				}
			}
		}
		else
		{
			symbolArray = symbol.split('|');
		}
		return symbolArray;
	};
	
	/**
	 ** This function searches for an existing instance of a news clip GUID within
	 ** a news clip GUID array and will remove it after adding it to the front of the array.
	 **/
	Cookie.BumpNewsClipArray = function(newsClipSerialized,newsClipArray)
	{
		if ( newsClipArray != null )
		{
			var subClipArray = newsClipSerialized.split('|');
			for(var iSubBump=0; iSubBump<subClipArray.length; iSubBump++)
			{
				var subString = subClipArray[iSubBump];
				var subComponents = subString.split(':');
				var subFlag = "N";
				if(subComponents.length == 2)
				{
					subFlag = subComponents[1];
				}
				var subGuid = subComponents[0];
				subString = subGuid + ":" + subFlag;
				newsClipArray.unshift(subString);
				for( var iBumpCounter=1;iBumpCounter<newsClipArray.length; iBumpCounter++ )
				{
					var newsString = newsClipArray[iBumpCounter];
					var newsComponents = newsString.split(':');
					var newsFlag = "N";
					if(newsComponents.length == 2)
					{
						newsFlag = newsComponents[1];
					}
					var newsGuid = newsComponents[0];
					if(newsGuid.toUpperCase() == subGuid.toUpperCase())
					{
						var aArray = newsClipArray.splice(iBumpCounter,(newsClipArray.length - iBumpCounter));
						aArray.shift();
						newsClipArray = newsClipArray.concat(aArray);
						if(newsFlag == "Y")
						{
							newsClipArray.shift();
							newsClipArray.unshift(subGuid + ":Y");  //read stories should remain read...
						}
					}
				}
			}
		}
		else
		{
			newsClipArray = newsClipSerialized.split('|');
		}
		return newsClipArray;
	};	
}

Cookie.prototype.RemoveNewsClip = function(guidString)
{
	var newsClipArray = this._newsClipArray;

	if(newsClipArray != null && newsClipArray.length > 0)
	{
		for(var iCount=0; iCount<newsClipArray.length; iCount++)
		{
			var thisClip = new NewsClip(newsClipArray[i]);
			if(thisClip.Guid.toUpperCase() == guidString.toUpperCase())
			{
				var aArray = newsClipArray.splice(iCount,(newsClipArray.length - iCount));
				aArray.shift();
				newsClipArray = newsClipArray.concat(aArray);
			}
		}
	}
};

Cookie.prototype.removeReadNewsClips = function()
{
	var newsClipArray = this._newsClipArray;
	var removedClips = new Array();
	var rclipi = 0;
	if(newsClipArray != null)
	{
		for(i = 0; i < newsClipArray.length; i++)
		{
			if(newsClipArray[i])
			{
				thisClip = new NewsClip(newsClipArray[i]);
				if(thisClip.ReadFlag == "Y")
				{
					newsClipArray.splice(i--,1);
					removedClips[rclipi++] = thisClip;
				}
			}
		}
	}
	return removedClips;
};

Cookie.prototype.setQuoteWithString = function(inputText,type)
{
	if(inputText != null && inputText.length>0)
	{
		var array = [];
		if(type != "nc=")
		{
			array = TransformSymbolStringToArray(inputText);
		}
		else
		{
			array = TransformNewsClipStringToArray(inputText);
		}
		this.setQuoteWithArray(array,type);
	}
};


Cookie.prototype.doesNewsClipExist = function(strGuid)
{
	strGuid = unescape(strGuid).toUpperCase();
	var clipArray = this.getQuoteArray("nc=");
	
	for(i = 0; i < clipArray.length;i++)
	{
		if(clipArray[i].indexOf(strGuid) > -1)
		{
			return true;
		}
	}
	return false;
};

Cookie.prototype.setQuoteWithArray = function(inputArray,type)
{
	if(inputArray != null)
	{
		this._isNewClip = false;  //set to false before the insert.
		var targetArray = this.getQuoteArray(type);
		for(var iCounter=inputArray.length-1; iCounter>=0; iCounter--)
		{
			var symbolString = inputArray[iCounter];
			if(type != "nc=")
			{
				targetArray = Cookie.BumpArray(symbolString,targetArray);
			}
			else
			{
				var iLengthBeforeBump = targetArray.length;
				targetArray = Cookie.BumpNewsClipArray(symbolString,targetArray);
				var iLengthAfterBump = targetArray.length;
				if(iLengthAfterBump > iLengthBeforeBump)
				{
					this._isNewClip = true;
				}
			}
		}
		this.setArray(targetArray,type);
		this.save();
	}
};

Cookie.prototype.removeNewsClips = function(guidString)
{
	if(guidString != null && guidString.length >=32)
	{
		guidString = unescape(guidString);
		var removeArray = guidString.split('|'); //headline^guid:Y|headline^guid:N|
		for(var i=0; i<removeArray.length; i++)
		{
			var removeVal = removeArray[i];
			var removeComponents = removeVal.split(':'); //headline^guid:Y
			var removeGuid = removeComponents[0].split['^'][1]; //headline^guid
			
			if(removeGuid != null && removeGuid.length == 32)
			{
				this._newsClipArray = Cookie.RemoveNewsClip(removeGuid, this._newsClipArray);
			}
		}
		this.save();
	}
};

Cookie.prototype.setArray = function(inputArray,type)
{
	var wellKnownValues = new WellKnownMWCookieValues();
	switch (type)
	{
		case wellKnownValues.GetViewedQuoteSectionHeader():
			this._viewedQuoteArray = inputArray;
			break;
		case wellKnownValues.GetSavedQuoteSectionHeader():
			this._savedQuoteArray = inputArray;
			break;
		case wellKnownValues.GetRecommendedQuoteSectionHeader():
			this._recommendedQuoteArray = inputArray;
			break;
		case wellKnownValues.GetNewsClipsSectionHeader():
			this._newsClipArray = inputArray;
			break;
		default:
	} 
};

Cookie.prototype.getQuoteArray = function(type)
{
	var returnArray = [];
	var wellKnownValues = new WellKnownMWCookieValues();
	switch (type)
	{
		case wellKnownValues.GetViewedQuoteSectionHeader():
			returnArray = this._viewedQuoteArray;
			break;
		case wellKnownValues.GetSavedQuoteSectionHeader():
			returnArray = this._savedQuoteArray;
			break;
		case wellKnownValues.GetRecommendedQuoteSectionHeader():
			returnArray = this._recommendedQuoteArray;
			break;
		case wellKnownValues.GetNewsClipsSectionHeader():
			returnArray = this._newsClipArray;
			break;
		default:
			return null;
	} 
	return returnArray;
};

Cookie.prototype.setValue = function(cookieValueString)
{
	this._value = cookieValueString;
	Cookie.SetMyMwCookieValue(cookieValueString);
};

Cookie.prototype.setSection = function(type)
{
	var wellKnownValues = new WellKnownMWCookieValues();
	switch (type)
	{
		case wellKnownValues.GetViewedQuoteSectionHeader():
			this._viewedQuoteArray = getSection(type);
			break;
		case wellKnownValues.GetSavedQuoteSectionHeader():
			this._savedQuoteArray = getSection(type);
			break;
		case wellKnownValues.GetRecommendedQuoteSectionHeader():
			this._recommendedQuoteArray = getSection(type);
			break;
		case wellKnownValues.GetNewsClipsSectionHeader():
			this._newsClipArray = getSection(type);
			break;
		default:
			return null;
	} 
};


Cookie.prototype.getValue = function()
{
	return this._value;
};

Cookie.prototype.getSection = function(type)
{
	var sectionArray = this._value.split('&');
	
	return Cookie.GetSection(sectionArray,type);
};

Cookie.prototype.save = function()
{
	this._value = this.buildCookieString(
							Cookie.ReturnArrayAsString(this._viewedQuoteArray),
							Cookie.ReturnArrayAsString(this._savedQuoteArray),
							Cookie.ReturnArrayAsString(this._recommendedQuoteArray),
							Cookie.ReturnArrayAsString(this._newsClipArray));
	Cookie.SetMyMwCookieValue(this._value);
};

Cookie.prototype.buildCookieString = function(viewedString,
										savedString,
										recommendedString,
										newsClipString)
{
	var wellKnownValues = new WellKnownMWCookieValues();
	var outputString = wellKnownValues.GenerateVersion();
	if(viewedString != null && viewedString.length>0)
	{
		outputString += ("&" + BreakApartSymbolsByCountry(viewedString,wellKnownValues.GetViewedQuoteSectionHeader()));
	}
	
	if(savedString != null && savedString.length>0)
	{
		outputString += ("&" + BreakApartSymbolsByCountry(savedString,wellKnownValues.GetSavedQuoteSectionHeader()));
	}
	
	if(recommendedString != null && recommendedString.length>0)
	{
		outputString += ("&" + BreakApartSymbolsByCountry(recommendedString,wellKnownValues.GetRecommendedQuoteSectionHeader()));
	}
	
	if(newsClipString != null && newsClipString.length>=32)
	{
		outputString += ("&" + Cookie.BuildNewsClipSection(newsClipString));
	}
	this._value = outputString;
	return outputString;
};

Cookie.prototype.clearAllNewsClips = function()
{
	if(this._newsClipArray)
	{
		this._newsClipArray = new Array();
		this.save();
	}
};

Cookie.prototype.clearAllViewedQuotes = function()
{
    if(this._viewedQuoteArray)
    {
        this._viewedQuoteArray = new Array();
        this.save();
    }
}

Cookie.prototype.load = function()
{
	var wellKnownValues = new WellKnownMWCookieValues();
	if(this._port)
	{
		var ports = this._port.split('&');
		for(i = 0; i < ports.length; i++)
		{
			var nmval = ports[i].split('=');
			if(nmval.length == 2)
			{
				eval("this." + nmval[0] + " = \"" + nmval[1] + "\"");
			}
		}
	}
	
	if(this._value != null && this._value.length>0)
	{
		var sectionArray = this._value.split('&');
		var sectionString = GetCookieSection(sectionArray,wellKnownValues.GetViewedQuoteSectionHeader());
		this._viewedQuoteArray = TransformSymbolStringToArray(sectionString);
		sectionString = GetCookieSection(sectionArray,wellKnownValues.GetSavedQuoteSectionHeader());
		this._savedQuoteArray = TransformSymbolStringToArray(sectionString);
		sectionString = GetCookieSection(sectionArray,wellKnownValues.GetRecommendedQuoteSectionHeader());
		this._recommendedQuoteArray = TransformSymbolStringToArray(sectionString);
		sectionString = GetCookieSection(sectionArray,wellKnownValues.GetNewsClipsSectionHeader());
		sectionString = unescape(sectionString);
		this._newsClipArray = TransformNewsClipStringToArray(sectionString);
	}
	else
	{
		this._viewedQuoteArray = [];
		this._savedQuoteArray = [];
		this._recommendedQuoteArray = [];
		this._newsClipArray = [];
	}
};

Cookie.prototype.reload = function()
{
	this.load();
};


/**
 ** This function hides the name of the cookie when
 ** calling the GetCookie function from Cookies.js
 **/
function MyMwCookieParser(testValue)
{
	var value = "";
	if(testValue != null && testValue.length > 0)
	{
		value = testValue;
	}
	else
	{
		value = GetCookie("mymw");
	}	
	var cookie = new Cookie();
	var viewedString = "";
	var savedString = "";
	var recommendedString = "";
	var newsClipString = "";
	var wellKnownValues = new WellKnownMWCookieValues();
	if(value != null && value.substring(1,2)== "e")
	{
		viewedString = GetSubSectionValue(value,wellKnownValues.GetViewedQuoteV3SectionHeader());
		cookie._viewedQuoteArray = TransformSymbolStringToArray(viewedString);
		savedString = GetSubSectionValue(value,wellKnownValues.GetSavedQuoteV3SectionHeader());
		cookie._savedQuoteArray = TransformSymbolStringToArray(savedString);
		recommendedString = GetSubSectionValue(value,wellKnownValues.GetRecommendedQuoteV3SectionHeader());
		cookie._recommendedQuoteArray = TransformSymbolStringToArray(recommendedString);
		cookie._value = value;
	}
	else if(value != null && value.substring(1,2)== "=")
	{
		viewedString = GetSubSectionValue(value,wellKnownValues.GetViewedQuoteSectionHeader());
		cookie._viewedQuoteArray = TransformSymbolStringToArray(viewedString);
		savedString = GetSubSectionValue(value,wellKnownValues.GetSavedQuoteSectionHeader());
		cookie._savedQuoteArray = TransformSymbolStringToArray(savedString);
		recommendedString = GetSubSectionValue(value,wellKnownValues.GetRecommendedQuoteSectionHeader());
		cookie._recommendedQuoteArray = TransformSymbolStringToArray(recommendedString);
		newsClipString = GetSubSectionValue(value,wellKnownValues.GetNewsClipsSectionHeader());
		cookie._newsClipArray = TransformNewsClipStringToArray(newsClipString);
		cookie._value = value;
	}
	
	return cookie;
}

function GetSubSectionValue(cookieValue,type)
{
	if(cookieValue != null)
	{
		var valueArray = cookieValue.split('&');
		var typeLength = type.length;
		for(var iTypeCounter = 0; iTypeCounter<valueArray.length; iTypeCounter++)
		{
			var valueString = valueArray[iTypeCounter];
			if(valueString.length >= typeLength && valueString.substring(0,typeLength)==type)
			{
				return valueString.substring(typeLength);
			}
		}
	}
	return "";
}

function WellKnownMWCookieValues()
{
	this._count = 1;
	
	WellKnownMWCookieValues.prototype.GenerateVersion = function()
	{
		return "v=4";
	};
	
	WellKnownMWCookieValues.prototype.GetViewedQuoteSectionHeader = function()
	{
		return "vq=";
	};
	
	WellKnownMWCookieValues.prototype.GetViewedQuoteV3SectionHeader = function()
	{
		return "viewedquotes=";
	};
	
	WellKnownMWCookieValues.prototype.GetSavedQuoteSectionHeader = function()
	{
		return "sq=";
	};
	
	WellKnownMWCookieValues.prototype.GetSavedQuoteV3SectionHeader = function()
	{
		return "savedquotes=";
	};

	WellKnownMWCookieValues.prototype.GetRecommendedQuoteSectionHeader = function()
	{
		return "rq=";
	};
	
	WellKnownMWCookieValues.prototype.GetRecommendedQuoteV3SectionHeader = function()
	{
		return "recommendedquotes=";
	};

	WellKnownMWCookieValues.prototype.GetNewsClipsSectionHeader = function()
	{
		return "nc=";
	};
}

/**
 **	This function is used in both Cookie and MyMwCookieParser objects.
 **/
function TransformSymbolStringToArray(sectionText)
{
	if( sectionText != null && sectionText.length > 0 )
	{
		var returnArray = [];
		var countryStringArray = sectionText.split('~');
		for( var iCountryCounter = 0; iCountryCounter < countryStringArray.length; iCountryCounter++)
		{
			var countryString = countryStringArray[iCountryCounter];
			var symbolArray = countryString.split('|');
			symbolArray = EnsureEachSymbolHasAssociatedExchange(symbolArray);
			returnArray = returnArray.concat(symbolArray);
		}
		return returnArray;
	}
	return null;
}

/**
 ** This function is used in the TransformSymbolStringToArray
 ** static function.
 **/
function EnsureEachSymbolHasAssociatedExchange(symbolArray)
{
	var previousExchange = "";
	if(symbolArray != null)
	{
		for ( var iEnsureCounter = 0; iEnsureCounter < symbolArray.length; iEnsureCounter++ )
		{
			var symbolString = symbolArray[iEnsureCounter];
			var components = symbolString.split(':');
			if(components.length == 1)
			{
				if(previousExchange == "")
				{
					previousExchange = "US";
				}
			}
			else if(components.length == 2)
			{
				if ( previousExchange != components[0] )
				{
					previousExchange = components[0].toUpperCase();
				}
				symbolString = components[1];
			}
			symbolArray[iEnsureCounter] = previousExchange + ":" + symbolString.toUpperCase();
		}
	}
	return symbolArray;
}

/**
 **	This function is used in both Cookie and MyMwCookieParser objects.
 **/
function TransformNewsClipStringToArray(textValue)
{
	if(textValue != null && textValue.length >= 32)
	{
		var newsClipArray = textValue.split('|');
		return newsClipArray;
	}
	else
	{
		return [];
	}
}

/**
 ** Used in BuildCookie to select a section within a cookie,
 ** splits this value into an array,
 ** removes redundant exchange symbols
 ** then builds an output string.
 **/
function BreakApartSymbolsByCountry(textValue,sectionHeader)
{	
	if( textValue != null && textValue.length > 0 )
	{
		var countryStringArray = textValue.split('~');
		var outputString = sectionHeader;
		var hasWrittenSymbols = false;
		for(var iCountryCounter = 0; iCountryCounter < countryStringArray.length; iCountryCounter++)
		{
			var countryString = countryStringArray[iCountryCounter];
			var symbolArray = countryString.split('|');
			symbolArray = AlterArrayByRemovingRedundantExchangeSymbols(symbolArray);
			for(var iSymbolArrayCounter=0;iSymbolArrayCounter<symbolArray.length;iSymbolArrayCounter++)
			{
				var symbolString = symbolArray[iSymbolArrayCounter];
				var componentArray = symbolString.split(':');
				if( componentArray.length == 2 )
				{
					if( hasWrittenSymbols == false )
					{
						if( componentArray[0] == "US" )
						{
							outputString += componentArray[1];
						}
						else
						{
							outputString += symbolString;
						}
						hasWrittenSymbols=true;
					}
					else
					{
						if( componentArray[0] == "US" )
						{
							outputString += ("~" + componentArray[1]);
						}
						else
						{
							outputString += ("~" + symbolString);
						}
					}
				}
				else
				{
					if( hasWrittenSymbols == false )
					{
						if( iSymbolArrayCounter != 0 )
						{
							outputString += ("|" + symbolString);
						}
						else
						{
							outputString += symbolString;
						}
						hasWrittenSymbols=true;
					}
					else
					{
						if( iSymbolArrayCounter != 0 )
						{
							outputString += ("|" + symbolString);
						}
						else
						{
							outputString += ("~" + symbolString);
						}
					}
					
				}
			}
		}
		return outputString;
	}
	return "";
}

/**
 ** Used within the static function BreakApartSymbolsByCountry.
 **/
function AlterArrayByRemovingRedundantExchangeSymbols(symbolArray)
{
	var previousExchange = "";
	
	for(var iAlterArrayCounter=0; iAlterArrayCounter<symbolArray.length; iAlterArrayCounter++)
	{
		var symbolString = symbolArray[iAlterArrayCounter];
		var components = symbolString.split(':');
		if( components.length == 2 )
		{
			var exchange = components[0];
			var symbol   = components[1];
			if( previousExchange.length == 0 )
			{
				previousExchange = exchange;
				//do nothing further with the array...
			}
			else
			{
				if( previousExchange == exchange )
				{	//modify the array to remove the exchange symbol
					symbolArray[iAlterArrayCounter] = symbol;
				}
				else
				{
					previousExchange = exchange;
				}	//do nothing further with the array...
			}
		} //don't bother with other scenarios...
	}
	return symbolArray;
}

/**
 ** This function builds a 32 character GUID using only random numbers.
 **/
function GetGuid()
{
	var guidValue = "";
	for(var iCounter = 0; iCounter < 32; iCounter++)
	{
		guidValue += Math.floor(Math.random() * 0xF).toString(0xF);
	}
	return guidValue;
}

/**
 ** This function randomly returns either 'Y' or 'N'.
 **/
function RandomYOrN()
{
	var flip = Math.random();
	if(flip>=0.5)
	{
		return "Y";
	}
	return "N";
}

/**
 ** Allows a JS developer to retrieve unread news clips from the cookie
 **/
function GetUnreadNewsClipGuids(newsClipText)
{
	return GetNewsClipGuidsByFlag(newsClipText,"N");
}

/**
 ** Allows a JS developer to retrieve read news clips from the cookie
 **/
function GetReadNewsClipGuids(newsClipText)
{
	return GetNewsClipGuidsByFlag(newsClipText,"Y");
}

function GetNewsClipGuidsByFlag(newsClipText,flag)
{
	if(newsClipText != null && newsClipText.length >0)
	{
		var wellKnownValues = new WellKnownMWCookieValues();
		var newsClipArray = newsClipText.split('|');
		var clipArray =[];
		for (var iGetReadGuidCounter=0; iGetReadGuidCounter<newsClipArray.length; iGetReadGuidCounter++)
		{
			var newsClipSerializedObject = newsClipArray[iGetReadGuidCounter];
			var components = newsClipSerializedObject.split(':');
			if(components.length==2 && components[1]==flag.toUpperCase())
			{
				clipArray.push(components[0]);
			}
		}
		return clipArray;
	}
}

function GetCookieSection(sectionArray,type)
{
	for(var iCount=0;iCount<sectionArray.length; iCount++)
	{
		var sectionString = sectionArray[iCount];
		if(sectionString.length > type.length)
		{
			var header = sectionString.substring(0,type.length);
			if(header == type)
			{
				return sectionString.substring(type.length);
			}
		}
	}
	return "";
}
