// ---------------------------------------
// BEGIN  AS --> JS Gateway Functionality
// ---------------------------------------



//flash to JS gateway
var uid = new Date().getTime();
var flashProxy = new FlashProxy(uid, 'flash/JavaScriptFlashGateway.swf');

// sample JS function
function checkDirty(arg) {
	var returnString  = "arg is "+arg+" from JS ";
	flashProxy.call("dirtyData", returnString);

}

// function to start flash from intro etc
function startFlash() {
	setTimeout("delayForLoad();",10);
}

function delayForLoad(){
	flashProxy.call("startClip");
}


function Exception(name, message)
{
    if (name)
        this.name = name;
    if (message) 
        this.message = message;  
}

/**
 * Set the name of the exception. 
 */
Exception.prototype.setName = function(name)
{
    this.name = name;
}

/**
 * Get the exception's name. 
 */
Exception.prototype.getName = function()
{
    return this.name;
}

/**
 * Set a message on the exception. 
 */
Exception.prototype.setMessage = function(msg)
{
    this.message = msg;
}

/**
 * Get the exception message. 
 */
Exception.prototype.getMessage = function()
{
    return this.message;
}

/**
 * Generates a browser-specific Flash tag. Create a new instance, set whatever
 * properties you need, then call either toString() to get the tag as a string, or
 * call write() to write the tag out.
 */

/**
 * Creates a new instance of the FlashTag.
 * src: The path to the SWF file.
 * width: The width of your Flash content.
 * height: the height of your Flash content.
 */
function FlashTag(src, width, height)
{
    this.src       = src;
    this.width     = width;
    this.height    = height;
    this.version   = '6,0,0,0';
    this.id        = null;
    this.bgcolor   = null;
    this.flashVars = null;
	this.wmode = null;
}

/**
 * Sets the Flash version used in the Flash tag.
 */
FlashTag.prototype.setVersion = function(v)
{
    this.version = v;
}

/**
 * Sets the ID used in the Flash tag.
 */
FlashTag.prototype.setId = function(id)
{
    this.id = id;
}

/**
 * Sets the background color used in the Flash tag.
 */
FlashTag.prototype.setBgcolor = function(bgc)
{
    this.bgcolor = bgc;
}
/** WSP inserted
*  Sets the wmode of the flash tag
*/
FlashTag.prototype.setWmode = function(wmode)
{
	this.wmode = wmode
}
/**
 * Sets any variables to be passed into the Flash content. 
 */
FlashTag.prototype.setFlashvars = function(fv)
{
    this.flashVars = fv;
}

/**
 * Get the Flash tag as a string. 
 */
FlashTag.prototype.toString = function()
{
    var ie = (navigator.appName.indexOf ("Microsoft") != -1) ? 1 : 0;
    var flashTag = new String();
    if (ie)
    {
        flashTag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
        if (this.id != null)
        {
            flashTag += 'id="'+this.id+'" ';
        }
        flashTag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+this.version+'" ';
        flashTag += 'width="'+this.width+'" ';
        flashTag += 'height="'+this.height+'">';
        flashTag += '<param name="movie" value="'+this.src+'"/>';
        flashTag += '<param name="quality" value="high"/>';
        flashTag += '<param name="bgcolor" value="#'+this.bgcolor+'"/>';
		flashTag += '<param name="wmode" value="#'+this.wmode+'"/>';
        if (this.flashVars != null)
        {
            flashTag += '<param name="flashvars" value="'+this.flashVars+'"/>';
        }
        flashTag += '</object>';
    }
    else
    {
        flashTag += '<embed src="'+this.src+'" ';
        flashTag += 'quality="high" '; 
        flashTag += 'bgcolor="#'+this.bgcolor+'" ';
        flashTag += 'width="'+this.width+'" ';
        flashTag += 'height="'+this.height+'" ';
		flashTag += 'wmode="'+this.wmode+'" ';
        flashTag += 'type="application/x-shockwave-flash" ';
        if (this.flashVars != null)
        {
            flashTag += 'flashvars="'+this.flashVars+'" ';
        }
        if (this.id != null)
        {
            flashTag += 'name="'+this.id+'" ';
        }
        flashTag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
        flashTag += '</embed>';
    }
    return flashTag;
}

/**
 * Write the Flash tag out. Pass in a reference to the document to write to. 
 */
FlashTag.prototype.write = function(doc)
{
    doc.write(this.toString());
}

/**
 * The FlashSerializer serializes JavaScript variables of types object, array, string,
 * number, date, boolean, null or undefined into XML. 
 */

/**
 * Create a new instance of the FlashSerializer.
 * useCdata: Whether strings should be treated as character data. If false, strings are simply XML encoded.
 */
function FlashSerializer(useCdata)
{
    this.useCdata = useCdata;
}

/**
 * Serialize an array into a format that can be deserialized in Flash. Supported data types are object,
 * array, string, number, date, boolean, null, and undefined. Returns a string of serialized data.
 */
FlashSerializer.prototype.serialize = function(args)
{
    var qs = new String();

    for (var i = 0; i < args.length; ++i)
    {
        switch(typeof(args[i]))
        {
            case 'undefined':
                qs += 't'+(i)+'=undf';
                break;
            case 'string':
                qs += 't'+(i)+'=str&d'+(i)+'='+escape(args[i]);
                break;
            case 'number':
                qs += 't'+(i)+'=num&d'+(i)+'='+escape(args[i]);
                break;
            case 'boolean':
                qs += 't'+(i)+'=bool&d'+(i)+'='+escape(args[i]);
                break;
            case 'object':
                if (args[i] == null)
                {
                    qs += 't'+(i)+'=null';
                }
                else if (args[i] instanceof Date)
                {
                    qs += 't'+(i)+'=date&d'+(i)+'='+escape(args[i].getTime());
                }
                else // array or object
                {
                    try
                    {
                        qs += 't'+(i)+'=xser&d'+(i)+'='+escape(this._serializeXML(args[i]));
                    }
                    catch (exception)
                    {
                        throw new Exception("FlashSerializationException",
                                            "The following error occurred during complex object serialization: " + exception.getMessage());
                    }
                }
                break;
            default:
                throw new Exception("FlashSerializationException",
                                    "You can only serialize strings, numbers, booleans, dates, objects, arrays, nulls, and undefined.");
        }

        if (i != (args.length - 1))
        {
            qs += '&';
        }
    }

    return qs;
}

/**
 * Private
 */
FlashSerializer.prototype._serializeXML = function(obj)
{
    var doc = new Object();
    doc.xml = '<fp>'; 
    this._serializeNode(obj, doc, null);
    doc.xml += '</fp>'; 
    return doc.xml;
}

/**
 * Private
 */
FlashSerializer.prototype._serializeNode = function(obj, doc, name)
{
    switch(typeof(obj))
    {
        case 'undefined':
            doc.xml += '<undf'+this._addName(name)+'/>';
            break;
        case 'string':
            doc.xml += '<str'+this._addName(name)+'>'+this._escapeXml(obj)+'</str>';
            break;
        case 'number':
            doc.xml += '<num'+this._addName(name)+'>'+obj+'</num>';
            break;
        case 'boolean':
            doc.xml += '<bool'+this._addName(name)+' val="'+obj+'"/>';
            break;
        case 'object':
            if (obj == null)
            {
                doc.xml += '<null'+this._addName(name)+'/>';
            }
            else if (obj instanceof Date)
            {
                doc.xml += '<date'+this._addName(name)+'>'+obj.getTime()+'</date>';
            }
            else if (obj instanceof Array)
            {
                doc.xml += '<array'+this._addName(name)+'>';
                for (var i = 0; i < obj.length; ++i)
                {
                    this._serializeNode(obj[i], doc, null);
                }
                doc.xml += '</array>';
            }
            else
            {
                doc.xml += '<obj'+this._addName(name)+'>';
                for (var n in obj)
                {
                    if (typeof(obj[n]) == 'function')
                        continue;
                    this._serializeNode(obj[n], doc, n);
                }
                doc.xml += '</obj>';
            }
            break;
        default:
            throw new Exception("FlashSerializationException",
                                "You can only serialize strings, numbers, booleans, objects, dates, arrays, nulls and undefined");
            break;
    }
}

/**
 * Private
 */
FlashSerializer.prototype._addName= function(name)
{
    if (name != null)
    {
        return ' name="'+name+'"';
    }
    return '';
}

/**
 * Private
 */
FlashSerializer.prototype._escapeXml = function(str)
{
    if (this.useCdata)
        return '<![CDATA['+str+']]>';
    else
        return str.replace(/&/g,'&amp;').replace(/</g,'&lt;');
}

/**
 * The FlashProxy object is what proxies function calls between JavaScript and Flash.
 * It handles all argument serialization issues.
 */

/**
 * Instantiates a new FlashProxy object. Pass in a uniqueID and the name (including the path)
 * of the Flash proxy SWF. The ID is the same ID that needs to be passed into your Flash content as lcId.
 */
function FlashProxy(uid, proxySwfName)
{
    this.uid = uid;
    this.proxySwfName = proxySwfName;
    this.flashSerializer = new FlashSerializer(false);
}

/**
 * Call a function in your Flash content.  Arguments should be:
 * 1. ActionScript function name to call,
 * 2. any number of additional arguments of type object,
 *    array, string, number, boolean, date, null, or undefined. 
 */
FlashProxy.prototype.call = function()
{

    if (arguments.length == 0)
    {
        throw new Exception("Flash Proxy Exception",
                            "The first argument should be the function name followed by any number of additional arguments.");
    }

    var qs = 'lcId=' + escape(this.uid) + '&functionName=' + escape(arguments[0]);

    if (arguments.length > 1)
    {
        var justArgs = new Array();
        for (var i = 1; i < arguments.length; ++i)
        {
            justArgs.push(arguments[i]);
        }
        qs += ('&' + this.flashSerializer.serialize(justArgs));
    }

    var divName = '_flash_proxy_' + this.uid;
    if(!document.getElementById(divName))
    {
        var newTarget = document.createElement("div");
        newTarget.id = divName;
        document.body.appendChild(newTarget);
    }
    var target = document.getElementById(divName);
    var ft = new FlashTag(this.proxySwfName, 1, 1);
    ft.setVersion('6,0,65,0');
    ft.setFlashvars(qs);
    target.innerHTML = ft.toString();
}

/**
 * This is the function that proxies function calls from Flash to JavaScript.
 * It is called implicitly.
 */
FlashProxy.callJS = function()
{
    var functionToCall = eval(arguments[0]);
    var argArray = new Array();
    for (var i = 1; i < arguments.length; ++i)
    {
        argArray.push(arguments[i]);
    }
    functionToCall.apply(functionToCall, argArray);
}


// ---------------------------------------
// end AS --> JS Gateway Functionality
// ---------------------------------------


/* this is specifically designed to expand and contract the mainnav div, for overlap prevention */
function openFlashNav(){
	document.getElementById('mainNav').style.height = "247px";  
}
function closeFlashNav() {
	document.getElementById('mainNav').style.height = "163px";
}


if (document.images) {
	var imageNames = new Array("footer_parents","footer_comments","footer_contact","footer_help","footer_privacy","footer_privacy_newburst","footer_rules","footer_allergen");
	var imagePath = "images/";
	var imageExtension = ".gif";
	var allMyImages = new Array(imageNames.length);
	var curName = "";
	var gWhichGlowing = "";
	
	for (var i=0; i<imageNames.length; i++) {
		curName = imageNames[i];
		allMyImages[curName] = new Array("over","out");
		allMyImages[curName]["out"] = new Image();
		allMyImages[curName]["out"].src = imagePath+curName+imageExtension;
		allMyImages[curName]["over"] = new Image();
		allMyImages[curName]["over"].src = imagePath+curName+"-over"+imageExtension;
	}
}

function Glow(whichImage) {
	if (document.images) {
		document[whichImage].src = allMyImages[whichImage]["over"].src;
		gWhichGlowing = whichImage;
	}
}

function DeGlow(){
	if (document.images) {
		document[gWhichGlowing].src = allMyImages[gWhichGlowing]["out"].src;
		gWhichGlowing = "";
	}
}
function printCheck() {
	if (window.print) {
		window.print();
	} else {
		alert("Please use the print function of your browser to print this page.");
	}
}

function windowPop(url, name, width, height, scrollboolean) {
	var params;
	if (scrollboolean != "") {
		params = "scrollbars="+scrollboolean;
	} else {
		params = "scrollbars=0";
	}
	params= params + ",location=0,menubar=0,status=1,toolbar=1,resizable=1,top=40,left=40,";
	params = params + "width=" + width + ",height=" + height; 
	window.open(url, name, params).focus();
}

function windowPopMySlurp(url, name, width, height, scrollboolean) {
	var params;
	if (scrollboolean != "") {
		params = "scrollbars="+scrollboolean;
	} else {
		params = "scrollbars=0";
	}
	params= params + ",location=0,menubar=0,status=0,toolbar=0,resizable=0,top=300,left=300,";
	params = params + "width=" + width + ",height=" + height; 
	window.open(url, name, params).focus();
}

function needCodePop(link) {
	if (link) {
		var win = window.open(link,'needcode_popup','width=449,height=317,menubar=no,resizable=no,status=no,toolbar=no');
		win.focus();
	}
		
	return false;
}

function sendIM(app,msg){
	var page = 'launch' + app + msg + '.html';
	//var myWindow = window.open(page, 'tinyWindow', 'width=10,height=10,left=6000,top=1');
	var s_click = s_gi(s_account);
	s_click.events='event4';s_click.linkTrackVars = 'events';s_click.linkTrackEvents = 'event4';s_click.tl(this, 'o', 'click tag');
	//self.setTimeout('winClose()',1000);
	if (app == 'aim'){
		window.open('aim:goim?message=You\'ve+got+to+check+out+Campbell\'s&reg;+SouperStar+Hawaii+Sweepstakes+and+Instant+Win+Game+at+http://www.mySlurp.com/?ref=aim++The+Grand+Prize+is+your+own+mansion+in+Hawaii+for+a+whole+week!','tinyWindow', 'width=10,height=10,left=6000,top=1');
	}else{
		window.open('ymsgr:sendIM?Select...&m=You\'ve+got+to+check+out+Campbell\'s&reg;+SouperStar+Hawaii+Sweepstakes+and+Instant+Win+Game+at+http://www.mySlurp.com/?ref=yahoo++The+Grand+Prize+is+your+own+mansion+in+Hawaii+for+a+whole+week!','tinyWindow', 'width=10,height=10,left=6000,top=1');
	}
}

function winClose() {
	var newwin = window.open('aimerror.html', 'tinyWindow', 'width=10,height=10')
	newwin.close();
}

function tagDownload(obj, type){
	var s_click = s_gi(s_account);
	s_click.events='event14';
	s_click.linkTrackVars = 'events,eVar9';
	s_click.linkTrackEvents = 'event14';
	s_click.eVar9 = type;
	s_click.tl(this, 'd', type);
}

function tagExternal(url){
	clickTag(1, url);
}

var tshirt = "tshirt_kids";

function changeTShirtDesign(whichShirt) {
	if (document.images)
	{
		document.tshirt.src = "images/" + whichShirt + ".gif";
		tshirt = whichShirt;
	}
}

function openTShirtPrintRev() {
	window.open('images/tshirt/' + tshirt + '_rev.pdf','Reverse','width=1160,height=925,toolbars=no,menubar=yes,location=no');
	var link = document.createElement('a');
	link.href = 'images/tshirt/' + tshirt + '_rev.pdf';
	tagDownload(link, 'TShirt Download (Reverse) - ' + tshirt);
}

function openTShirtPrint() {
	window.open('images/tshirt/' + tshirt + '.pdf','Regular','width=1160,height=925,toolbars=no,menubar=yes,location=no');
	var link = document.createElement('a');
	link.href = 'images/tshirt/' + tshirt + '_rev.pdf';
	tagDownload(link, 'TShirt Download - ' + tshirt);
}

function videoPop(link) {
	if (link) {
		var win = window.open(link.href,'video_popup','width=417,height=335,menubar=no,resizable=no,status=no,toolbar=no');
		win.focus();
	}
		
	return false;
}

function previewMessagePop(senderName, friendName, section, featureid) {
	var win = window.open('previewmessage.aspx?senderName='+senderName+'&featureid='+featureid+'&friendName='+friendName+'&section='+section,'message_popup','width=550,height=415,menubar=no,resizable=no,status=no,toolbar=no');
	win.focus();
		
	return false;
}

function testpop(){

//document.write('<a href="' + url + '" target="_blank" id="newwindow"></a>');
document.getElementById('poppy').click();
		var url = "test.html";//"needcode.aspx?isGame=true";
		var w = 450;
		var h = 320;
		var xPos = (screen.width - w) / 2;
		var yPos = (screen.height - h) / 2;
		popupbrowser = window.open ( url, "poppy", "toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,height=" + h + ",width=" + w + ",left=" + xPos + ",top=" + yPos +"");
		popupbrowser.focus();

}

function addFavorite(featureID) {
	var pic1 = new Image(1,1); 
	pic1.src = "datacontroller.aspx?action=addfavorite&featureID=" + featureID + "&nocache=" + Math.random(5);
	var panel = document.getElementById("addpanel");
	panel.style.display = "none";
	var panel = document.getElementById("infavoritespanel");
	panel.style.display = "block";
	flashProxy.call("dirtyData");
	return false;
}

function reloadData(){
	flashProxy.call("dirtyData");
	// return false;
}

function loadIcon(url) {
	var imgFormat = ".gif";
	var iconBase = "images/buddyicons/";
	var serverPath = location.href.substring(0,location.href.lastIndexOf("/") + 1);
	var fullPath = serverPath + iconBase + url + imgFormat;
	//window.location = "aim:buddyicon?src=" + fullPath;
	
	var link = document.createElement('a');
	link.href = fullPath;
	tagDownload(link, 'Buddy Icon Download');
	
	var fullURL = 'loadbuddyicon.aspx?src=' + fullPath;
	var myWindow = window.open(fullURL, 'tinyWindow', 'width=10,height=10,left=4000,top=1');
	self.setTimeout('winClose()', 1000);	
}


// functions to set custom avatar and theme color values from flash widget on registration/change my look page
function setIcon(gender,skinTone,hairStyle,hairColor,bg) {
		document.getElementById("Gender").value = gender;
		document.getElementById("SkinTone").value = skinTone;
		document.getElementById("HairStyle").value = hairStyle;
		document.getElementById("HairColor").value = hairColor;
		document.getElementById("BgColor").value = bg;
}

function setTheme(theColor) {
		document.getElementById("ThemeColor").value = theColor;
}

function writeSouperSlide(siteroot) {
	var so;
	so = '<object classid="clsid:166B1BCA-3F9C-11CF-8075-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=10,0,0,0" ID=SOUPERSLIDE width=600 height=440>';
	so = so + '<param name=src value="flash/SOUPERSLIDE.dcr">';
	so = so + '<param name=swRemote value="swSaveEnabled=\'false\' swVolume=\'true\' swRestart=\'true\' swPausePlay=\'true\' swFastForward=\'true\' swContextMenu=\'false\' ">';
	so = so + '<param name=sw1 value="3">';
	so = so + '<param name=sw2 value="0">';
	so = so + '<param name=sw3 value="' + siteroot + '/souperslide.aspx">';
	so = so + '<param name=sw4 value="' + siteroot + '/datacontroller.aspx">';
	so = so + '<param name=swStretchStyle value=fill>';
	so = so + '<PARAM NAME=bgColor VALUE=#444444>';
	so = so + '<embed src="flash/SOUPERSLIDE.dcr" sw1="3" sw2="0" sw3="' + siteroot + '/souperslide.aspx" sw4="' + siteroot + '/datacontroller.aspx" bgColor=#444444  width=600 height=440 swRemote="swSaveEnabled=\'false\' ';
	so = so + 'swVolume=\'true\' swRestart=\'true\' swPausePlay=\'true\' swFastForward=\'true\' swContextMenu=\'false\' " swStretchStyle=fill ';
	so = so + ' type="application/x-director" pluginspage="http://www.macromedia.com/shockwave/download/"></embed>';
	so = so + '</object>';
	document.write(so);
}

/*==========================================================================# 
# * Function for adding a Filter to an Input Field                          # 
# * @param  : [filterType  ] Type of filter 0=>Alpha, 1=>Num, 2=>AlphaNum   # 
# * @param  : [evt         ] The Event Object                               # 
# * @param  : [allowDecimal] To allow Decimal Point set this to true        # 
# * @param  : [allowCustom ] Custom Characters that are to be allowed       # 
#==========================================================================*/ 
function filterInput(filterType, evt, allowDecimal, allowCustom){ 
	var keyCode, Char, inputField, filter = ''; 
	var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
	var num   = '0123456789'; 
	// Get the Key Code of the Key pressed if possible else - allow 
	if(window.event){ 
		keyCode = window.event.keyCode; 
		evt = window.event; 
	}else if (evt)keyCode = evt.which; 
	else return true; 
	// Setup the allowed Character Set 
	if(filterType == 0) filter = alpha; 
	else if(filterType == 1) filter = num; 
	else if(filterType == 2) filter = alpha + num; 
	if(allowCustom)filter += allowCustom; 
	if(filter == '')return true; 
	// Get the Element that triggered the Event 
	inputField = evt.srcElement ? evt.srcElement : evt.target || evt.currentTarget; 
	// If the Key Pressed is a CTRL key like Esc, Enter etc - allow 
	if((keyCode==null) || (keyCode==0) || (keyCode==8) || (keyCode==9) || (keyCode==13) || (keyCode==27) )return true; 
	// Get the Pressed Character 
	Char = String.fromCharCode(keyCode); 
	// If the Character is a number - allow 
	if((filter.indexOf(Char) > -1)) return true; 
	
	// Else if Decimal Point is allowed and the Character is '.' - allow 
	else if(filterType == 1 && allowDecimal && (Char == '.') && inputField.value.indexOf('.') == -1)return true; 
	else return false; 
}

function findScreenRes(){
	/* Core functionality in place, the rest will come when I get some sleep */
	var width = screen.width;
	var height = screen.height;
	var objTagCollection = document.body.getElementsByTagName("p");
	var searchString = "";
	
	if (height < 601){
		searchString = "800";
	}
	else if (height < 769){
		searchString = "1024";
	
	}
	else if (height > 769){
		searchString = "1280";
	}
	
	for (i=0; i<objTagCollection.length; i++) {
		if(objTagCollection[i].id.indexOf(searchString)>-1){
			objTagCollection[i].className = "active";
		}
	}
}
function trackCodeEntry(code, featureid){
	var featurename;
	
	switch (featureid){
	case "3":
		featurename = "Souperslide";
		break;
	}
	//clickTag('x4', 'GameCodeEntry:' + featurename + ' - ' + code);
}

function openNeedCodeGames()
	{
		var url = "needcode.aspx?isGame=true";
		var w = 450;
		var h = 320;
		var xPos = (screen.width - w) / 2;
		var yPos = (screen.height - h) / 2;
		popupbrowser = window.open ( url, "_help", "toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,height=" + h + ",width=" + w + ",left=" + xPos + ",top=" + yPos +"");
		popupbrowser.focus();
	};
	
// This replaces sage_ev
function clickTag(n, v)
{
	//sage_ev(n, v);
}

// This empty function is to keep the topnav flash from throwing a js error vs. having to update the flash to remove obsolete tagging calls.
function sageflash() {

}

// These empty functions are to keep the SlurpNBurp flash game from throwing a js error vs. having to update the flash to remove obsolete tagging calls.
function cmCreatePageviewTag() {

}
function cmCreateConversionEventTag() {

}



