$(function() {
	createWallpaperDialog();
	$(window).resize(checkReposition);
	DC.setTimer()
});

var desktopPopUp = null;
var sDEF='_def.';
var sOFF='_off.';
var sROLL='_roll.';
var sSEL='_on.';
function imgRoll(oImg,bClear){
	if(oImg.src.indexOf('_on')==-1 || bClear){
		if(bClear){
			oImg.src=oImg.src.replace(sSEL,sDEF);
		}else if(oImg.src.indexOf('roll')==-1){
			oImg.src=oImg.src.replace(sDEF,sROLL);
		}else{		
			if(oImg.className.indexOf('selected')==-1){
				oImg.src=oImg.src.replace(sROLL,sDEF);
			}
		}
	}
}
function checkReposition() {
	if( !oFlashContainer ) return; 
	var sizeArr = oFlashContainer.getResizeInfo();
	//_height, _width, _scaleFactor
	// sizeArr[0], sizeArr[1], sizeArr[2]
	
	if( ( sizeArr[0] /  zInterface.flashDefaultSize().height < 1) && ( sizeArr[1] / zInterface.flashDefaultSize().width  < 1 ) ){
		zInterface.handleResize( zInterface.flashDefaultSize().height, zInterface.flashDefaultSize().width, 1.01 )
	}
}

function getBuckets(){
	
	var bucketStr = stripslashes( GetCookie( 'buckets' ) );
	
	if( bucketStr == null || bucketStr == "null" || bucketStr.length <=0 ){
		bucketStr = "[]";
	}
	
	//if there are quote, strip'em
	if( bucketStr.substring(0,1) == "\"")
		bucketStr = bucketStr.substring( 1, bucketStr.length );
	if( bucketStr.substring(bucketStr.length-1,bucketStr.length) == "\"" )
		bucketStr = bucketStr.substring( 0, bucketStr.length-1 );
		
	if( bucketStr == null || bucketStr == "null" || bucketStr.length <=0 ){
		bucketStr = "[]";
	}
	return bucketStr;
}

function getFDSAgreement(){
	var fAgree = GetCookie("fdsa");
	if( fAgree == null || fAgree == "null" || fAgree.length <=0 ){
		fAgree = " |false";
	}
	return fAgree;
}

function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Brant Messenger (http://www.brantmessenger.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str + '').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
        case '\\':
            return '\\';
        case '0':
            return '\u0000';
        case '':
            return '';
        default:
            return n1;
        }
    });
}


function showDesktop( _additionalQueryParams ){
	_additionalQueryParams = typeof(_additionalQueryParams) == undefined ? "" : _additionalQueryParams;
	var bNeedsNewPop = true;
	if(desktopPopUp){
		try {
			var x = desktopPopUp.location.href;
			bNeedsNewPop = false;
			desktopPopUp.focus() 
		}
		catch( e ){
			bNeedsNewPop = true;
		}
	}
	if( bNeedsNewPop ){
		var feat = "scrollbars=yes,toolbar=no,menubar=no,status=no,location=no,resizable=yes,top=0,left=0,width=" + window.screen.availWidth + ",height=" + window.screen.availHeight;
		desktopPopUp = window.open( "main.jhtml?experience=desktop" + _additionalQueryParams, "ZwinkyDesktop", feat )
		
		desktopPopUp.focus();
		$("#" + id).remove( );
		zInterface.Ads.hideCurrent();
		$("body").css("background", "#a0bbd6 url(http://assets.zwinky.com/homepage/desktopSplash3.jpg) center top no-repeat");
		$("body").html("<div style=\"width:996px; height:740px; margin: 0px auto;\" > </div>"+
			"<div style=\"width:420px; margin:-450px auto; position:relative;\" > "+
			"<div style=\"width:207px; height:244px; float:left; cursor:hand; cursor: pointer;\" id=\"launchRegular\"></div>"+
			"<div style=\"width:207px; height:244px; float:left; cursor:hand; cursor:pointer;\" id=\"launchDesktop\"></div>"+
			"</div>");
			
		$("#launchDesktop").click(function(){
			urchinTracker('/clicks/web/beta/launch/desktop');
			showDesktop("");
		});
		$("#launchRegular").click(function(){
			urchinTracker('/clicks/web/beta/launch/regular');
			hideDesktop();
		});
	}
}

function hideDesktop( _additionalQueryParams ){
	//We are the pop up window, refresh the opener
	if(window.opener){
		try {
			var y = window.opener.location.href ;
			window.opener.location.href = window.opener.location.href;
			window.close();
		}
		catch( e ){
			window.open( "main.jhtml?experience=browser" + _additionalQueryParams, "Zwinky" );
			window.close();
		}	
	}
	//We are the original window, close popup and refresh
	else if( desktopPopUp ){
		//try and make sure that the window still exists...
		try {
			var x = desktopPopUp.location.href;
			desktopPopUp.close();
		}
		catch( e ){}
		
		document.location.href = document.location.href;
	}
	//we are the pop up, opener is closed, close self and open new window
	else{
		window.open( "main.jhtml?experience=browser" + _additionalQueryParams, "Zwinky" );
	}	
}



/**
 * DATA CONTROL INTERACTIONS
 **/
function dataChangedCB(){

	//save current values
	var iCurVer = oData.currentUser.versionNumber;
	var sCurUsr = oData.currentUser.username;

	//load latest data
	updateData();

	if ( oFlashContainer && oData.currentUser.username != sCurUsr ) {
		oFlashContainer.onUserChanged( oData.currentUser );
	} 
	else if ( oFlashContainer && oData.currentUser.versionNumber!=iCurVer ) {		
		oFlashContainer.onOutfitChanged( oData.currentUser );
	}
}

function dataChangedZBucks(zb,zc,pb,ts) {
	if( oFlashContainer ) {
		oFlashContainer.onCurrencyChange( {zbucks:zb,lifetime:zc,pbucks:pb} );
	}
}

function dataChangedZBucksReload() {
	if( oFlashContainer ) {
		oFlashContainer.onZBucksReload();
	}
}

function createWallpaperDialog(){
	$("#WallPaperDialog").dialog("destroy").dialog({
		autoOpen:false,
		draggable:true,
		resizable:false,
		modal:true,
		overlay:{opacity:.6,background:"black"},
		dialogClass:"",
		position:"center",
		width:446,
		height:310,
		show:{effect:"fade",speed:500},
		hide:{effect:"fade",speed:250},
		open:function(){
		},
		close:function(){
		}
	}).show();
	$('.ui-dialog-titlebar-close').css("display","none");
	
	$("#WallPaperCloseBtn").click(function(){closeModal("WallPaperDialog")});
	$("#WallPaperCancelBtn").click(function(){closeModal("WallPaperDialog")});
	$("#WallPaperDoneBtn").click(function(){closeModal("WallPaperDialog")});
	
	$("#WallPaperCancelBtn").hover(
		function(){
			$("#WallPaperCancelBtn_over").show();
			$("#WallPaperCancelBtn_up").hide();
		},
		function(){
			$("#WallPaperCancelBtn_over").hide();
			$("#WallPaperCancelBtn_up").show();
		}
	);
	
	$("#WallPaperDoneBtn").hover(
		function(){
			$("#WallPaperDoneBtn_over").show();
			$("#WallPaperDoneBtn_up").hide();
		},
		function(){
			$("#WallPaperDoneBtn_over").hide();
			$("#WallPaperDoneBtn_up").show();
		}
	);
}

function showWallpaperDialog(a_imgSrc){
	$("#WallPaperImage").attr("src",a_imgSrc);
	$("#WallPaperImage").css("width", "104px");
	$("#WallPaperImage").css("height", "118px");
	$("#WallPaperDialog").dialog("open");
}

var zInterface = new (function ZwinktopiaInterface() {	
	var applicationHeight;
	var applicationWidth;
	var applicationScaleFactor;
	var isRegOpen = false;
	var tbFinishCallback = null;
	var tbUID = null;

	this.triggerOutfitChange = function() {
		if( oData ) {
			if( oData.currentUser.versionNumber >= 0 )oData.currentUser.versionNumber++;
			else oData.currentUser.versionNumber = 1;
			setData();
		}
	};
	
	this.getTBPartnerVal = function() {
		return TOOLBAR.sPartnerID;
	};
	
	this.getToolbarId = function() {
		return oToolbarController.sUID;
	};
	
	this.showWallPaper = function( a_url){
		showWallpaperDialog(a_url);
	};
	this.postToFacebook = function( url ) {
	/*
			FB.ui({
				method: 'feed',
				name: 'Zwinky',
				link: 'http://www.zwinky.com',
				picture: url,
				caption: 'www.zwinky.com',
				description: 'some description',
				message: 'some message'
			});
		return;
	*/
		var attachment = {'media': [{'type':'image',
		    'src':url,
		    'href':'http://www.zwinky.com/'}]};
		FB.Connect.streamPublish("" , attachment);
		return;
	};
	
	this.postToGigya = function( url ) {
		showGigya(url, '');
	};
	
	this.postToMyspace = function( url ) {
		showGigya(url, 'myspace');
	};
	this.postToTwitter = function( url ) {
		showGigyaShortenURL(url, 'twitter');
	};
	
	this.setLoggedIn = function( username ) {
		sUsername = username;
		DC.username = username;
		
	};
	this.setPartnerCode = function( _partner ) {
		partnerCode = _partner;
		
		// need to reinstantiate run run js to pass in partner value
		if( _partner && !TOOLBAR.bInstalled) {
			this.determineRunRunSupport();
		}
	}
	
	this.setLoggedOut = function() {
		sUsername = null;
	};
	
	this.determineRunRunSupport = function() {
		var jsElem = document.getElementById("jsRunRun" );
		if( document.getElementById("jsRunRun" ) ) {
			jsElem.parentNode.removeChild(jsElem);
			var installJS = document.createElement('script'); installJS.setAttribute("type","text/javascript"); installJS.setAttribute("async",false);
			installJS.setAttribute("id","jsRunRun" );
			installJS.setAttribute("src", "http://free.zwinky.com/dl/install_js.jhtml?partner="+partnerCode+"&product=zwinky&bInstantiateToolbar=false&bCustomFinishHandler=true")
			document.getElementsByTagName("head")[0].appendChild(installJS);
		} else {
			
			var toolbarJS = document.createElement('script'); toolbarJS.setAttribute("type","text/javascript"); toolbarJS.setAttribute("async",false);
			toolbarJS.setAttribute("id", "jsToolbar" );
			toolbarJS.setAttribute("src", "http://dp.smileycentral.com/download/toolbarDetect/toolbar.js")
			document.getElementsByTagName("head")[0].appendChild(toolbarJS);	
	
			var installJS = document.createElement('script'); installJS.setAttribute("type","text/javascript"); installJS.setAttribute("async",false);
			installJS.setAttribute("id","jsRunRun" );
			installJS.setAttribute("src", "http://free.zwinky.com/dl/install_js.jhtml?partner="+partnerCode+"&product=zwinky&bInstantiateToolbar=false&bCustomFinishHandler=true")
			document.getElementsByTagName("head")[0].appendChild(installJS);
		}
	
	};
	
	this.launchGame = function( id ) {
		// only pass webmode=true if the user is NOT logged in
		var sWebModeStr = "";
		var gameParams = "width=550,height=410,titlebar=no,status=no,scroll=no";
		if ( !sUsername || sUsername <= 3 ) 
			sWebModeStr = "&webmode=true"; 
		
		switch( id ){
			case 29:
			case "29":
				gameParams = "width=413,height=551,titlebar=no,status=no,scroll=no"; 
			break;
		}
			
		var gameWindow = window.open(sGameWinURL + "?gameID="+id+"&source=web"+sWebModeStr,"gw",gameParams);
		if( !gameWindow ) {
			alert( "You have a popup-blocker enabled. Please allow popups for www.zwinky.com" );
		}
	};
		
	this.launchKeepsake = function( date ) {
		if ( $("#zKeepsake").size() ) {
			return;
		}
		
		var overlay = $(
			'<div id="zKeepsake" >' + 
			'	<iframe src="' + sKeepsakeURL + '" frameborder="0"></iframe>' + 
			'</div>'
		);
		
		$("iframe", overlay).bind("load", function () {
			$(this).css("visibility", "visible");
		});
		
		$("#flashContainer").append(overlay);	
	
	};
	
	this.closeKeepsake = function() {
		$("#zKeepsake").remove();
	};
	
	this.regStartOver = function() {
		$("#zRegistration").remove();
		isRegOpen = false;
		oFlashContainer.regStartOver();
	};
	
	this.launchQuestTracker = function() {
		if ( $("#zQuestTracker").size() != 0 ) {
			return;
		}
		var overlay = $(
			'<div id="zQuestTracker" >' + 
			'	<iframe src="' + sQuestTrackerURL  + '" frameborder="0"></iframe>' + 
			'</div>'
		);
		
		$("iframe", overlay).bind("load", function () {
			$(this).css("visibility", "visible");
		});
		$("#flashContainer").append(overlay);	
	};
	
	this.closeQuestTracker = function() {
		$("#zQuestTracker").remove();
	};
	
	
	
	this.launchProfile = function( user ) {
		urchinTracker('/clicks/web/launch/profile');
		window.open( sProfileURL + sUsername );
	};
	
	this.launchProfileNewWindow = function( user ) {
		urchinTracker('/clicks/web/launch/profilenew');
		window.open(sProfileURL + user);
	};
	
	this.launchPurchaseZCard = function( user ) {
		// to switch between opening a dialog or a new window
		if (bUseCommerceDialog){
			var overlay = $(
				'<div id="zCardPurchase" >' + '</div>'
			);		
			$("#flashContainer").append(overlay);		
			$("#zCardPurchase").dialog({
				height: 600,
				width: 950,
				modal: true,
				resizable: false,
				close: function(e,ui){ $("#zCardPurchase").remove();},
				open: function (e,UI){
					$("#zCardPurchase").append('<iframe id="zCardPurchaseIframe" src="'+sZcardPurchaseURL+'" frameborder="0"></iframe>')
					
				}
			});
			$("#zCardPurchase").dialog("open");
		}
		else {
			// any of the section on the end causes scrollbars to disappear, which we need for pay pal
			//window.open(sZcardPurchaseURL,"_blank","directories=no,location=0,menubar=no,toolbar=no,titlebar=no,status=no")
			window.open(sZcardPurchaseURL,"_blank")
		}
		
		/*
		This code was loading the iframe twice, resulting in double tracking
			
			var overlay = $(
				'<div id="zCardPurchase" >' +
					'<iframe id="zCardPurchaseIframe" src="'+sZcardPurchaseURL+'" frameborder="0"></iframe>' +
				'</div>'
			);
			$("iframe",overlay).bind("load", function() {
				$(this).css("visibility", "visible");
				$( "#zCardPurchase" ).dialog({
				height: 600,
				width: 950,
				modal: true,
				resizable: false,
				close: function(e,ui){ $("#zCardPurchase").remove();}				
			});
			});
			$("#flashContainer").append(overlay);
		 */
		urchinTracker('/clicks/web/launch/commerce-main');
		logUnifiedEvent( "ModalCommerce", {Action:"init"} );
		//window.open( sZcardPurchaseURL + user, "zcardpuchase" );
	};
	
	this.launchBetaLearnMore = function() {
//		window.open( "http://blog.zwinky.com/view_article/Must-Know-Info-About-Beta.html?id=1466" );
//		window.open( "http://blog.zwinky.com/2011/08/15/fashion-design-studio-in-beta" );
//		window.open( "http://blog.zwinky.com/?p=1731" );
//		window.open( "http://blog.zwinky.com/?p=2204" );
		window.open( "http://blog.zwinky.com/?p=2432" ); 
	};
	
	this.openWindowWithOptions = function( url, options ) {
		if( url.indexOf( "/commerce/purchase.jhtml") >= 0 ) {
			this.launchPurchaseZCard();
		} else {
			window.open( url, "wzw"+Math.floor(Math.random()*10000), options );
		}
	};
	
	this.openWindowToURL = function( url ) {
		var openedWindow = window.open( url );
		if( !openedWindow ) 
			alert( "You have a popup-blocker enabled. Please allow popups for www.zwinky.com" );
		
	};
	
	this.launchEarnZCard = function( ) {
		urchinTracker('/clicks/web/launch/commerce-offers');
		window.open( sZcardOffersUrl, "zcardearn" );
	};
	
	this.launchZnotes = function( user ) {
		urchinTracker('/clicks/web/launch/znotes');
		window.open( sEnoteUrl + "&l=all&v=viewall&username=" + sUsername, "znote" );
	};
	
	this.goHome = function() {
		location.href = sHomepage;
	};
	
	this.reloadApplication = function() {
		location.href = location.href;
	};	
	
	this.redirectWindow = function( _url ) {
		location.href = _url;
	};	
	
	this.switchExperience = function( _goFullScreen, _additionalQueryParams ) {
		if( _goFullScreen )
			showDesktop( _additionalQueryParams );
		else
			hideDesktop( _additionalQueryParams );	
	};
	
	this.launchRegistration = function() {	
		if ( $("#zRegistration").size() )
			return;
		var sCurRegisterURL = sRegisterURL;
		if( typeof( partnerCode ) != "undefined" ) {
			sCurRegisterURL += "&partnerCode=" + partnerCode;
		}
		var overlay = $(
			'<div id="zRegistration">' + 
			'	<div class="loading"></div>' + 
			'	<iframe src="' + sCurRegisterURL + '" frameborder="0"></iframe>' + 
			'</div>'
		);

		$("#flashContainer").append(overlay);	
		
		this.showRegistration();
	};
	
	this.isRegOpen = function() {
		return isRegOpen;
	};
	
	this.showRegistration = function() {
		var iframe = $("#zRegistration iframe");
		zInterface.handleResize( -1, -1, -1 );
		var ready;
		try {
			ready = iframe[0].contentWindow.registrationReady;
		}
		catch (e) {}	

		if (!ready) {
			setTimeout(function() { zInterface.showRegistration() }, 500);
			return;
		}
		zInterface.handleResize( -1, -1, -1 );
		$("#zRegistration .loading").remove();
		iframe.css("visibility", "visible");	
		isRegOpen = true;
		logUnifiedEvent( "RegistrationStart_JS" );
	};
	
	//Calls up to flash, checks to see if they are in the DC, and if they can
	//rock out.
	this.confirmAge = function( _age, _email ){
		return oFlashContainer.confirmAge( _age, _email );
	};
	
	this.launchGreetingOverlay = function( sUrl ) {	
		if ( $("#zGreeting").size() ) {
			return;
		}
		
		var overlay = $(
			'<div id="zGreeting">' + 
			'	<div class="loading"></div>' + 
			'	<iframe src="' + sUrl + '" frameborder="0"></iframe>' + 
			'</div>'
		);
		
		$("#flashContainer").append(overlay);	
	};
	
	this.viewAllZwink = function() {
		window.location = "http://blog.zwinky.com/";
	};
	
	this.promptLogin = function() {
		oFlashContainer.promptLogin();
	};
	
	this.goToURL = function( url ) {
		window.location = url;
	};
	
	this.facebookConnect = function() {
		FbCommon.fBLogin();
	};
	
	this.facebookRegister = function() {
		window.open(
			sContextPath+"/FBExternal.jhtml?v=1&action=connect", 
			"fbConnect",
			"top=50,left=50,resizable=yes,scrollbars=no,menubar=no,width=750,height=600"
		);
	};
	
	this.facebookNowWhat = function() { 
		FbCommon.handleConnectedClick();
	};
	
	this.facebookLogout = function() {
		FwpConnect.logout();
	};

	this.userRegistered = function( oUser ) {
		oFlashContainer.onUserRegisterStrings( oUser.username, oUser.zbucks, oUser.zcards, oUser.zchievements );
		this.closeRegistration();
	};
	
	this.savePasswordFromReg = function( pwd ) {
	
		oFlashContainer.onSavePasswordFromReg( pwd );
	};
	
	this.closeRegistration = function() {
		$("#zRegistration").remove();
		isRegOpen = false;
	};
	 
	this.facebookLinked = function( data ) {
		if (!data.isLinked) {
			return;
		}	
	};
	
	// this is really a check to see if they need to be redirected to DLP
	this.hasToolbarInstalled = function() {
		//if( bDev ) return true;
		return zw_toolbarCheck( true );
	};
	this.hasToolbarInstalledForRealz = function() {
		// hasToolbarInstalled() also returns true for OTB path, sometimes I just 
		// need to know if there is a tb installed	
		return zw_toolbarCheckWithoutOTB( true );
	};
	this.gotoDLP = function() {
		//this.promptToolbarInstall( "organic", null );
		location.href = downloadURL +"&utm_id=18";
	};
	
	this.optionalToolbarFlow1 = function() {
		if (this.tbUID != null){
			oFlashContainer.optionalTBInstalled(true,this.tbUID);
		}
		else{
			oFlashContainer.optionalTBInstalled(true,oSettingsCtrl.I);
		}		
	};
	
	this.organicInstallComplete = function() {
		alert( "Organic install complete" );
	};
	
	this.firePreRegistrationPixel = function() {
		firePreRegPixel()
	};
	
	this.fireRegistrationPixel = function() {
		fireRegPixel();
	};
	
	this.promptToolbarInstall = function( mode ) {
		
		
		if( mode == "organic" ) {
			finishRunRun = function() {

				$("#dvEasy").remove();
				
				urchinTracker("/clicks/otb/toolbarinstalled");
				
				
				CreateSettingsCtrl();

				var ver=oSettingsCtrl.GetVersion('');			

				var tb_uid = oSettingsCtrl.I;

				var tb_partner = oSettingsCtrl.P;
				
				this.tbUID = tb_uid;

				if( tbFinishCallback && typeof(tbFinishCallback) == "function" ) tbFinishCallback();
				
			};
			oDownloadCtrl.HandleResult=function(result){ 
				switch(result){ 
					case -300 : 
					case 0 : 
						if (result == -300){ 
							this.SetStatusMsg("You already have the Zwinky Toolbar toolbar installed"); 
							urchinTracker("/runruninstaller/alreadyinstalled");
						}else{ 
							this.SetStatusMsg("Congratulations, the Zwinky Toolbar toolbar has been successfully installed!"); 
							urchinTracker("/runruninstaller/installsuccess");
						} 
						this.CompleteProgressBar(); 
						break; 
					case -107 : 
						oEasyCtrl.Cancel(); 
						urchinTracker("/runruninstaller/installcancelled");
						break; 
					case -301 : 
						this.SetStatusMsg("The Zwinky Toolbar toolbar download is successful!"); 
						urchinTracker("/runruninstaller/installsuccess2");
						this.CompleteProgressBar(); 
						break; 
					default : 
						this.LoadError(result); 
						urchinTracker("/runruninstaller/someerror");
						break; 
				}
				
				bRunRunInstalled = true;
			}
			tbFinishCallback = zInterface.organicInstallComplete;
			$( "#dvModalPromptInstall" ).dialog({
				dialogClass: 'dvModalPromptUpsell',
				width: 660,
				height: 388,
				modal: true,
				draggable: false,
				resizable: false
				});
			$( "#btnPromptInstall" ).mouseover( function() {$(this).addClass("over").removeClass("out");} );
			$( "#btnPromptInstall" ).mouseout( function() {$(this).addClass("out").removeClass("over");} );
			$( "#btnPromptClose" ).mouseover( function() {$(this).addClass("over").removeClass("out");} );
			$( "#btnPromptClose" ).mouseout( function() {$(this).addClass("out").removeClass("over");} );
			$( "#btnPromptClose" ).click( function() {$("#dvModalPromptInstall").dialog("close");} );
			$( "#btnPromptInstall" ).click( function() {$("#dvModalPromptInstall").dialog("close");installToolbar();} );
		} else {
			if( mode == "commerce" ) $("#zCardPurchase").remove();
			tbFinishCallback = zInterface.optionalToolbarFlow1;
			oFlashContainer.showOTBDialog();
		}
	};
	
	this.otbRunRunInstall = function() {
		finishRunRun = function() {

			$("#dvEasy").remove();
			
			urchinTracker("/clicks/otb/toolbarinstalled");
			
			
			CreateSettingsCtrl();

			var ver=oSettingsCtrl.GetVersion('');			

			var tb_uid = oSettingsCtrl.I;

			var tb_partner = oSettingsCtrl.P;
			
			this.tbUID = tb_uid;

			zInterface.optionalToolbarFlow1();
			
		};
		oDownloadCtrl.HandleResult=function(result){ 
			switch(result){ 
				case -300 : 
				case 0 : 
					if (result == -300){ 
						this.SetStatusMsg("You already have the Zwinky Toolbar toolbar installed"); 
						urchinTracker("/runruninstaller/alreadyinstalled");
					}else{ 
						this.SetStatusMsg("Congratulations, the Zwinky Toolbar toolbar has been successfully installed!"); 
						urchinTracker("/runruninstaller/installsuccess");
					} 
					this.CompleteProgressBar(); 
					break; 
				case -107 : 
					oEasyCtrl.Cancel(); 
					urchinTracker("/runruninstaller/installcancelled");
					break; 
				case -301 : 
					this.SetStatusMsg("The Zwinky Toolbar toolbar download is successful!"); 
					urchinTracker("/runruninstaller/installsuccess2");
					this.CompleteProgressBar(); 
					break; 
				default : 
					this.LoadError(result); 
					urchinTracker("/runruninstaller/someerror");
					break; 
			}
			
			bRunRunInstalled = true;
		}
		installToolbar();
	};
	
	this.search = function( type, keywords ) {
		var url;
		switch ( type ) { 
			case "Images": url = "AJimage"; break;
			case "News":   url = "AJnews";  break;
			default:       url = "AJmain";
		}
		
		var search = "http://search.mywebsearch.com/mywebsearch/" + url + 
						".jhtml?st=site&tpr=zwinky&searchfor=" + escape(keywords);
		
		var href = "http://search.mywebsearch.com/mywebsearch/cfg_redir2.jhtml" + 
						"?id=" + oToolbarController.sPartnerID +
						"&ptb=" + oToolbarController.sUID + 
						"&url=" + search;

		window.location = href;		
	};		
		
	var leftShade;
	var rightShade;
	var bottomShade;
	var flash = { width: 974, height: 745 };
	
	this.flashDefaultSize = function(){
		return flash;
	}
	
	$(function() {
		leftShade = $("#shadeLeft");
		rightShade = $("#shadeRight");
		bottomShade = $("#shadeBottom");
	});
	
	this.setShade = function( state ) {				
		this.resizeShade();		

		if ( state ) {
			$(window).resize( this.resizeShade );
			this.Ads.hide();
		}
		else {
			$(window).unbind( "resize", this.resizeShade );
			this.Ads.show();
		}
		
		$.each( [leftShade, rightShade, bottomShade], function() {
			state ? this.show() : this.hide();
		});
	};
	
	this.resizeShade = function() {	
		// IE 8
		if ( $.browser.msie && $.browser.version == "8.0" ) {
			var width = Math.max( 0, $(document).width() - flash.width - 21 );
			var height = Math.max( 0, $(document).height() - flash.height );
			
			leftShade.css( "width", Math.floor( width / 2 ) );
			rightShade.css( "width", Math.ceil( width / 2 ) );
			bottomShade.css( "height", height );
		}
		// IE <= 7
		else if ( $.browser.msie ) {
			var width = Math.max( 0, $(document).width() - flash.width );
			var height = Math.max( 0, $(document).height() - flash.height );
			
			leftShade.css( "width", Math.floor( width / 2 ) );
			rightShade.css( "width", Math.ceil( width / 2 ) );
			bottomShade.css( "height", height );
		}
		// Firefox, etc
		else {
			var width = Math.max( 0, $(document).width() - flash.width );
			var height = Math.max( 0, $(document).height() - flash.height );
			
			leftShade.css( "width", width / 2 );
			rightShade.css( "width", width / 2 );
			bottomShade.css( "height", height );
		}	
	};
		
	this.trace = function( str ) {
		$("#flashDebugger").append( str + "<br/>" );
	};
	
	this.reportAbuse = function ( _userList, _chatHistory ){
		$("#ul").val( _userList ); 
		$("#cl").val( _chatHistory ); 
		$("#reportAbuse").submit();
	};
	
	this.handleResize = function ( _height, _width, _scaleFactor ){
		
		applicationHeight = _height <= 0 ? applicationHeight : _height;
		applicationWidth = _width <= 0 ? applicationWidth : _width;
		applicationScaleFactor = _scaleFactor <= 0 ? applicationScaleFactor : _scaleFactor;
		 
		var extraWidth = ($("#flashContainer").width() - applicationWidth < 0) ? 0 : $("#flashContainer").width() - applicationWidth ;
		var flashContainerWidth = $("#flashContainer").width() < zInterface.flashDefaultSize().width ? zInterface.flashDefaultSize().width : $("#flashContainer").width();
		var flashContainerHeight = $("#flashContainer").width() < zInterface.flashDefaultSize().height ? zInterface.flashDefaultSize().height : $("#flashContainer").width();
		
		//console.log(extraWidth);
		//Handle FB Like
		$("#FBLikeBox").css("top", "-1px");
		$("#FBLikeBox").css("left", ( ( flashContainerWidth - ( extraWidth / 2 ) ) - ( 258 * applicationScaleFactor ) ) +"px" );
//		(flash object's x position)+(content width/2)-(registrration iframe's width/2)
		
		if( $("#zRegistration").length >= 1){
			$("#zRegistration").css("top" , (110 * applicationScaleFactor ) + ( ( $("#zRegistration").height() * ( applicationScaleFactor - 1 ) / 2 ) ) +"px")
			$("#zRegistration").css("left" , ( ( flashContainerWidth / 2 ) - ( $("#zRegistration").width() / 2 ) + ( 15 * applicationScaleFactor) )+"px")
		}
					
		/* permanent ads */
		if (zInterface.Ads.sideBarAd.enabled){
			var bHasRoom = extraWidth/2 > 160;			
			if ($("#adSideBar").length>0){			
				if (bHasRoom){
					var left = 0;
					var leftover = ((extraWidth/2 - 160)/2 );					
					if (leftover < 25){
						left = (flashContainerWidth - ( extraWidth / 2 ) + leftover );
					}else{
						left = (flashContainerWidth - ( extraWidth / 2 ) + 25 );
					}
					
					$("#adSideBar").css("left", left + "px");
					$("#adSideBar").css("top", (152 * applicationScaleFactor) + "px").show();		
				}else{
					$("#adSideBar").hide();
				}
			}else{
				if (bHasRoom){
					zInterface.Ads.sideBarAd.init()
				}
			}
		}
			
		if(!zInterface.Ads.bShowingAds)
			return;
		
		var adHeight = $("#flashContainer > .ad").height();
		var adWidth = $("#flashContainer > .ad").width();	
		
		if( zInterface.Ads.currAd == null)
			return;	
		//console.log ('scale: ' + applicationScaleFactor);
		//console.log ('flashContainerHeight: ' + flashContainerHeight);
		switch( zInterface.Ads.currAd.code ) {
			case "zwinky_signedout":
				$("#flashContainer > .ad").css( "top", (440 * applicationScaleFactor) + ( (adHeight * ( applicationScaleFactor - 1) /2 ) ) + "px");
				$("#flashContainer > .ad").css( "left", ( ( flashContainerWidth - ( extraWidth / 2 ) ) - ( (adWidth + 7 ) * applicationScaleFactor ) ) + ( adWidth * ( applicationScaleFactor -1 ) /2 )  +"px" );
				break;
			case "zwinky_games":
				$("#flashContainer > .ad").css( "top", (430 * applicationScaleFactor) + ( (adHeight * ( applicationScaleFactor - 1) /2 ) ) + "px");
				$("#flashContainer > .ad").css( "left", ( ( extraWidth / 2 ) + ( 30 * applicationScaleFactor ) ) + ( adWidth * ( applicationScaleFactor -1 ) /2 )  +"px" );			
				break;
			case "zwinky_shopping":
				$("#flashContainer > .ad").css( "top", (430 * applicationScaleFactor) + ( (adHeight * ( applicationScaleFactor - 1) /2 ) ) + "px");
				$("#flashContainer > .ad").css( "left", ( ( flashContainerWidth - ( extraWidth / 2 ) ) - ( (adWidth + 7 ) * applicationScaleFactor ) ) + ( adWidth * ( applicationScaleFactor -1 ) /2 )  +"px" );
				break;
			case "zwinky_Inworld":
				var disableWall = false;
				switch(zInterface.Ads.currAd.div){
					case "adBusStop":
						topPos =  (185 * applicationScaleFactor) + (((250 * applicationScaleFactor)-250)/2); // + ( (adHeight * ( applicationScaleFactor - 1) /2 ) )
						$("#flashContainer > .ad").css( "top", topPos  + "px");
						left = ( extraWidth / 2 ) + (240 * applicationScaleFactor) + (((300 * applicationScaleFactor)-300)/2);
						$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;
						break;
					break;
					case "adWardrobe":
						topPos =  (613 * applicationScaleFactor) + (((90 * applicationScaleFactor)-90)/2);
							$("#flashContainer > .ad").css( "top", topPos  + "px");
						left =   (applicationWidth - 728)/2 + ( extraWidth / 2 ) ;
							$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;
					break
					case "adCreator":
						topPos =  (565 * applicationScaleFactor) + (((90 * applicationScaleFactor)-90)/2);
							$("#flashContainer > .ad").css( "top", topPos  + "px");
						left =   (applicationWidth - 728)/2 + ( extraWidth / 2 ) ;
							$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;
					break
					case "adStadium":
						var start = (60 * applicationScaleFactor) + 114.8; // linear magic						
						topPos =  (start * applicationScaleFactor) + (((90 * applicationScaleFactor)-90)/2);
							$("#flashContainer > .ad").css( "top", topPos  + "px");
						left = (applicationWidth - 728)/2 + ( extraWidth / 2 ) ; // center
							$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;		
					break;
					case "adBeach":
						var start = (60 * applicationScaleFactor) + 110; // linear magic						
						topPos =  (start * applicationScaleFactor) + (((90 * applicationScaleFactor)-90)/2);
							$("#flashContainer > .ad").css( "top", topPos  + "px");
						left = (applicationWidth - 900)/2 + ( extraWidth / 2 ) ; // center
							$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;				
					break;
					case "adArcade":
						var start = (160 * applicationScaleFactor) + 4.8; // linear magic						
						topPos =  start;
							$("#flashContainer > .ad").css( "top", topPos  + "px");
						left = (applicationWidth - 757)/2 + ( extraWidth / 2 ) ; // center
							$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;			
					break;
					case "adZeeplex":
						var start = (160 * applicationScaleFactor) + 4.8; // linear magic								
						topPos =  start;
							$("#flashContainer > .ad").css( "top", topPos  + "px");
						left = (applicationWidth - 495)/2 + ( extraWidth / 2 ) ; // center
							$("#flashContainer > .ad").css( "left",  left +"px" );
						disableWall = true;				
					break;
					case "adHomepageSignedIn":
						topPos = (587.912 * applicationScaleFactor) - 127.791;
						left = (extraWidth/2) + ((714.286 * applicationScaleFactor) - 70);
						// don't ever ask
						if ($.browser.msie){
							if (applicationScaleFactor < 1.02 && flashContainerHeight > 1100 ){
								if (flashContainerHeight < 1264 ){
									topPos -= 1;
									left -= 1;
								}else{
									topPos += 4;								
									left += 3;
								}
							}else if (applicationScaleFactor < 1.02){
								topPos -= 4;
								left -= 2
							}else if (applicationScaleFactor > 1.02 && applicationScaleFactor < 1.04){
								left -= 4;
								topPos -= 3;
							}
						}
						$("#flashContainer > .ad").css( "top", topPos + "px");
						$("#flashContainer > .ad").css( "left", left  +"px" );	
					break;
				
				}
				if (disableWall){
					/*
					var adLocation = {
						x : left - extraWidth/2,
						w : 300,
						y : 0,
						h : 250
					}
					if (zInterface.Ads.currAd.sz){
						adLocation.w = zInterface.Ads.currAd.sz.split("x")[0];
						adLocation.h = zInterface.Ads.currAd.sz.split("x")[1];
					}*/
					//console.log(adLocation)
					oFlashContainer.disableWallClick();
				}
				if (zInterface.Ads.sideBarAd.enabled){
					if (zInterface.Ads.currAd.div == "adCreator")
						$("#adSideBar").css("top", (112 * applicationScaleFactor) + "px");	
					else
						$("#adSideBar").css("top", (152 * applicationScaleFactor) + "px");	
				}
				break;
		}
			
			
	};
	
	this.refreshDataController = function( _username ){
		oFlashContainer.dcIsDirty( _username ); 
	};
	
	this.setFDSAgreement = function ( _hasAgreed ){
		setCookie( "fdsa", _hasAgreed, '', '/', '.zwinky.com');
	};
})();


zInterface.Ads = {	
	currAd: null,
	bShowingAds: false,
	bRegistrationHit : false,
	nCreatorHit : 0,
	timer : null,
	nTimeout : 60000,
	items: {
		home_signedout: {
			div: "adHomepage",
			code: "zwinky_signedout",
			sz: "300x250",
			location: "home_signedout"
		},
		games: {
			div: "adGames",
			code: "zwinky_games",
			sz: "300x250",
			location: "games"
		},
		shopping: {
			div: "adShopping",
			code: "zwinky_shopping",
			sz: "300x250",
			location: "shopping"
		},
		sidebar: {
			div: "adSideBar",
			code: "zwinky_Inworld",
			sz: "160x600",
			location: "sidebar"
		},
		wardrobe: {
			div: "adWardrobe",
			code: "zwinky_Inworld",
			sz: "728x90",
			location: "wardrobe"
		},
		creator: {
			div: "adCreator",
			code: "zwinky_Inworld",
			sz: "728x90",
			location: "creator"
		},
		stadium1: {
			div: "adStadium",
			code: "zwinky_Inworld",
			sz: "728x90",
			location: "stadium1"
		},
		beach1: {
			div: "adBeach",
			code: "zwinky_Inworld",
			sz: "728x90",
			location: "beach1"
		},
		arcade1: {
			div: "adArcade",
			code: "zwinky_Inworld",
			sz: "728x90",
			location: "arcade1"
		},
		movie_theater2: {
			div: "adZeeplex",
			code: "zwinky_Inworld",
			sz: "300x250",
			location: "movie_theater2"
		},
		movie_theater3: {
			div: "adZeeplex",
			code: "zwinky_Inworld",
			sz: "300x250",
			location: "movie_theater3"
		},
		home_signedin: {
			div: "adHomepageSignedIn",
			code: "zwinky_Inworld",
			sz: "300x250",
			location: "home_signedin"
		}		
	},
	
	changeView: function( section ) {
		/**
		 *  2 things to note: 
		 *	1) when you register and end up on home signed in, the creator sends a false changeview section, bRegistration hit keeps track of that to prevent it later on from showing the wrong ad
		 *	2)When you hit creator in register, there is a false hide ad call, nCreator count keeps track that on the 2nd changeview to creator, we don't hide ads (see hideCurrent)
		 **/
		// for issue 2
		if (section == "creator" || section =="simplifiedcreator"){
			this.nCreatorHit++;
		}else{
			this.bCreatorHit = 0;
		}
		// for issue 1
		if (section == "registration" || section == "home_signedin"){
			this.bRegistrationHit = true;
			//console.log('set fake out system cause section = ' + section)
		}else if (section == "creator" && this.bRegistrationHit){
			this.bRegistrationHit = false;
			//console.log('fake out')
			return;
		}else if (section != "creator" && section != "wardrobe" && section != "home_signedin" && section !="simplifiedcreator"){
			this.bRegistrationHit = false;
			//console.log('reset fake out system cause section = ' + section)
		}
		// normal behavior
		//console.log(section);
		this.insert( section );
	},
	
	insert: function( page ) {
		$("#flashContainer > .ad").remove();
		
		var item = this.items[page];
		if ( !item ) {
			return;
		}		
		this.currAd = item;
		this.bShowingAds = true;
		
		var div;
		
		if (item.sz == undefined){
			item.sz = "300x250";
		}
		
		if (item.code.indexOf("zwinky_Inworld") == 0){
			div =  $('<div id="' + item.div + '" class="ad">' + 									
					'<iframe src="ad.jhtml?code=' + item.code + '&sz=' + item.sz + '&lctn=' +  item.location + '" frameborder="0"></iframe>' +
					'<div class="overlay"></div>' +
					'</div>');
		}else {		
			div = $('<div id="' + item.div + '" class="ad">' + 
					'	<h2>Advertisement</h2>' +					
					'<iframe src="ad.jhtml?code=' + item.code + '&sz=' + item.sz + '&lctn=' +  item.location + '" frameborder="0"></iframe>' +
					'</div>');
		}
		
		
		clearInterval(this.timer)
		this.timer = setInterval('zInterface.Ads.refreshAd()',this.nTimeout)
					
		if ( !this.visible ) {
			div.hide();
		}
		
		if (this.bStickToHiddenAd){
			div.hide();
		}
		$("#flashContainer").append( div );
		zInterface.handleResize( -1, -1, -1 );
		
	},
	refreshAd: function(){
		var iframe = $("#flashContainer > .ad iframe")[0]
		if (iframe){
			iframe.src = iframe.src.split("&v=")[0] + "&v=" + Math.random();
		}
	},
	// this boolean is ussed to override showCurrent ad. In the case of dialogs, sometimes a load finishes and wants to show ads. If the dialog set to stick to hidden, it will ignore that. the dialog will reset that on close
	bStickToHiddenAd : false,
	hideCurrent: function(setStick) {
		if (setStick){
			this.bStickToHiddenAd = true;
			//console.log('set stick')
		}		
		//console.log('hide ads')
		// for issue 1, see changeview
		if (this.nCreatorHit == 2){
			this.bCreatorHit = 0;
			//console.log('fakeout creator hide ads')
			return;
		}	
		this.bShowingAds = false;
		if( this.visible ) $("#flashContainer > .ad").hide();	
	},
	showCurrent: function(resetStick) {
		if (resetStick){
			this.bStickToHiddenAd = false;
			//console.log('reset stick')
		}
		if (!this.bStickToHiddenAd){
			//console.log('show ads')
			this.bShowingAds = true;
			if( this.visible ) $("#flashContainer > .ad").show();
		}else{
			//console.log('not show ads due to stick')
		}
		
	},
	hide: function() {
		this.bShowingAds = false;
		$("#flashContainer > .ad").hide();
		this.visible = false;
	},
	
	show: function() {
		this.bShowingAds = true;
		$("#flashContainer > .ad").show();
		this.visible = true;
	},
	
	visible: true,
	
	sideBarAd : {
		enabled : true,
		init : function (){
			var item = zInterface.Ads.items.sidebar;		
			if (this.enabled){
				var div =  $('<div id="' + item.div + '" class="ad160">' + 									
						'<iframe src="ad.jhtml?code=' + item.code + '&sz=' + item.sz + '&lctn=' +  item.location + '" frameborder="0"></iframe>' +
						'<div class="overlay"></div>' +
						'</div>');
				$('#flashContainer').append(div);
				setInterval('zInterface.Ads.sideBarAd.refreshAd()',zInterface.Ads.nTimeout)
				zInterface.handleResize( -1, -1, -1 );				
			}
		},
		refreshAd : function (){
			if ($('#adSideBar:visible').length > 0){
				var iframe = $('#adSideBar iframe')[0];
				iframe.src = iframe.src.split("&v=")[0] + "&v=" + Math.random();
			}
		}
	}
};

var bFlashReady = false;
var bDataControlReady = false;
var oFlashContainer;
function onFlashReady() {
	oFlashContainer = swfobject.getObjectById("flashShell");
	zInterface.handleResize( -1, -1, -1 );		
	
	if ( sUsername && bLoggedIn ) {
		oFlashContainer.initialize( {
			username: sUsername,
			zbucks: iZbucks,
			zcards: iZcards,
			zchievements: iZchievements,
			facebook: false					
		});
	}
	
}
function logUnifiedEvent( eventName, eventBody ) {
	_Anemone.logEvent(eventName, eventBody );
}

function CreateSettingsCtrl(){

	var sCtrlHTML='<object id="SettingsControl" classid="CLSID:151885bd-6ddd-47df-9266-da3f86e1f5fe" width="1" height="1"></object>';

	if (!window.ActiveXObject) {

		navigator.plugins.refresh(false);

		sCtrlHTML='<embed id="SettingsControl" type="application/x-zwinky_42plugin" ProgId="Zwinky_42.SettingsPlugin" width="1" height="1"></embed>';

	}

	var oDiv=document.createElement('div');

	oDiv.innerHTML=sCtrlHTML

	document.body.appendChild(oDiv);	

	oSettingsCtrl=document.getElementById("SettingsControl");				

}


