function launchSkin(page,utm_id,params) {
	if ( typeof(tbCheck) != "function" ){ return false; }
	if ( tbCheck() ) {
		var launchStr = "";
		
		//is this Dev?
		var devStr = "";
		if ( location.href.indexOf("dev.") > -1 ) {
			devStr = "dev=1&";
		};
		
		if ( page == null ) {
			page = "wardrobe";
			launchStr = "HKLM,SOFTWARE\\MyWebSearch\\SkinTools,PlayerPath, Avatar wardrobe?" + devStr;
		}
		else if ( page == "chat" || page == "desktop" || page == "accWardrobe" || page == "keepsake" || page == "game" || page == "questdialog" || page == "roomeditor"|| page=="directwardrobe") {
			launchStr = "HKLM,SOFTWARE\\MyWebSearch\\SkinTools,PlayerPath, Avatar "+page+"?" + devStr + params;
		}
		else{
			launchStr = "HKLM,SOFTWARE\\MyWebSearch\\SkinTools,PlayerPath, Avatar wardrobe?" + devStr + page;
		}
		
		if (window.ActiveXObject) {
			document.getElementById('SettingsControl').Launch(launchStr);
		}
		else {
			page = "wardrobe";
			document.getElementById('ToolbarCtlMWS').Launch(launchStr);
		}
		
		try{urchinTracker('/clicks/web/launch/'+page);}catch(e){}
	}
	else {
		window.location.href=downloadURL+"&utm_id=" + (utm_id ? utm_id : 18);
	}
}

function launchWardrobe( params ) {
	launchSkin( params ? params : "wardrobe" );
}

/**
 * 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",
		height:"auto",
		width:446,
		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() {	
	this.triggerOutfitChange = function() {
		if( oData ) {
			if( oData.currentUser.versionNumber >= 0 )oData.currentUser.versionNumber++;
			else oData.currentUser.versionNumber = 1;
			setData();
		}
	};
	
	this.getTBPartnerVal = function() {
		return partnerParam;
	};
	
	this.getToolbarId = function() {
		return oToolbarController.sUID;
	};
	
	this.showWallPaper = function( a_url){
		showWallpaperDialog(a_url);
	};
	this.postToFacebook = function( url ) {
		var isConnected = function() {
			var attachment = { media: [ { type: "image",
		                              src: url,
		                              href: "http://www.zwinky.com/" } ] };		
			FB.Connect.streamPublish( "", attachment );		
		};
		
		var notConnected = function() {
			FbCommon.fBLogin();
		};
				
		FB.Connect.ifUserConnected( isConnected, notConnected );
	};
	
	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;
		try {
			updateDataUser( new oUser( username ) );
		} catch ( e ) {}
	};
	
	this.setLoggedOut = function( username ) {
		sUsername = null;
		try {
			updateDataUser( new oUser() );
		} catch ( e ) {}
	};
	
	this.launchGame = function( id ) {
		// only pass webmode=true if the user is NOT logged in
		var sWebModeStr = "";
		if ( !sUsername || sUsername <= 3 ) sWebModeStr = "&webmode=true";
		window.open(sGameWinURL + "?gameID="+id+"&source=web"+sWebModeStr,"gw","width=550,height=410,titlebar=no,status=no,scroll=no");
	};
		
	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.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.ShowQuestInfoDialog = function( quest, task ) {
		launchSkin( "questdialog", "direct", "quest="+quest+"&task="+task );
	};
	
	this.launchWardrobeToSpeciesCategory = function( species, category ) { 
		launchSkin( "directwardrobe", "direct", "wardrobespecies="+species+"&wardrobecategory="+category );
	};
	
	this.launchRoomEditorToCategory = function( category ) {
	
		launchSkin( "roomeditor", "direct", "roomeditorcategory="+category );
	};
	
	this.launchGetRoom = function() {
		this.launchRoom( "school1" );
	};
	
	this.launchRoom = function( room_id ) {
		launchSkin( "chat", "directroom", "room=" + room_id );
	};
	
	this.launchWardrobe = function() {
		launchSkin( "wardrobe", "wardrobe" );
	};
	
	this.launchChat = function() {
		launchSkin( "chat", "chat" );
	};
	
	this.launchProfile = function( user ) {
		location.href = sProfileURL + user;
	};
	
	this.launchPurchaseZCard = function( user ) {
		window.open( sZcardPurchaseURL + user, "zcardpuchase" );
	};
	
	this.launchEarnZCard = function( ) {
		window.open( sZcardOffersUrl, "zcardearn" );
	};
	
	this.launchZnotes = function( user ) {
		location.href = sEnoteUrl + "&l=all&v=viewall&username=" + user;
	};
	
	this.goHome = function() {
		location.href = sHomepage;
	};
	
	this.launchRegistration = function() {	
		if ( $("#zRegistration").size() ) {
			return;
		}
		
		var overlay = $(
			'<div id="zRegistration">' + 
			'	<div class="loading"></div>' + 
			'	<iframe src="' + sRegisterURL + '" frameborder="0"></iframe>' + 
			'</div>'
		);
		
		$("#flashContainer").append(overlay);	
		
		this.showRegistration();
	};
	
	this.showRegistration = function() {
		var iframe = $("#zRegistration iframe");
		
		var ready;
		try {
			ready = iframe[0].contentWindow.registrationReady;
		}
		catch (e) {}	

		if (!ready) {
			setTimeout(function() { zInterface.showRegistration() }, 500);
			return;
		}
		
		$("#zRegistration .loading").remove();
		iframe.css("visibility", "visible");	
	};
	
	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 ) {
		oUser.refreshCurrency = true;
		oUser.hasCreatorOutfit = false;
		oFlashContainer.onUserRegister( oUser );
	};
	
	this.closeRegistration = function() {
		$("#zRegistration").remove();
	};
	 
	this.facebookLinked = function( data ) {
		if (!data.isLinked) {
			return;
		}	
		
		oFlashContainer.onUserChanged( { 
			facebook : true,
			username: data.linkedUserName,
			refreshCurrency: true
		} );
	};
	
	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: 970, height: 745 };
	$(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/>" );
	};
})();


zInterface.Ads = {	
	items: {
		home_signedout: {
			div: "adHomepage",
			code: "zwinky_signedout"
		},
		games: {
			div: "adGames",
			code: "zwinky_games"
		},
		shopping: {
			div: "adShopping",
			code: "zwinky_shopping"
		}
	},
	
	changeView: function( section ) {
		this.insert( section );
	},
	
	insert: function( page ) {
		$("#flashContainer > .ad").remove();
		
		var item = this.items[page];
		if ( !item ) {
			return;
		}		
		
		var div = $('<div id="' + item.div + '" class="ad">' + 
					'	<h2>Advertisement</h2>' +					
					'	<iframe src="ad.jhtml?code=' + item.code + '" frameborder="0"></iframe>' +
					'</div>');
					
		if ( !this.visible ) {
			div.hide();
		}

		$("#flashContainer").append( div );
	},
	
	hide: function() {
		$("#flashContainer > .ad").hide();
		this.visible = false;
	},
	
	show: function() {
		$("#flashContainer > .ad").show();
		this.visible = true;
	},
	
	visible: true
};

var bFlashReady = false;
var bDataControlReady = false;
var oFlashContainer;

function onFlashReady() {
	oFlashContainer = swfobject.getObjectById("flashShell");
	
	if ( sUsername && bLoggedIn ) {
		oFlashContainer.initialize( {
			username: sUsername,
			zbucks: iZbucks,
			zcards: iZcards,
			zchievements: iZchievements,
			facebook: false					
		});
	}
}


$(function() {
	initData();
	
	//load user sUsername
	var newUser = new oUser();
	newUser.username = sUsername;
	
	try {
		updateDataUser(newUser);
	} 
	catch (e) {
		//console.log("caught firefox error", e);
	}
	
	bDataControlReady = true;
	
	//initFlash();
	createWallpaperDialog();

});