/*
 *	GAME LOGIC OBJECT
 *
*/
if (typeof(console) === "undefined") {
	console = {
		log: function(){}
	};
}

var constants = {
    DESIGNER                : '1',
    STOREOWNER              : '2',
    LARGE_GARMENT_SIZE      : {height:480,width:220},
    SMALL_GARMENT_SIZE      : {height:240,width:110},
    GARMENT_TYPES           : {"tops":1,"outfits":2,"dresses":3,"bottoms":6,"shoes":7,"accessories":8},
    GARMENT_TYPES_ARR       : ["","tops","outfits","dresses","","","bottoms","shoes","accessories"],
	GARMENT_TYPES_MYSTUFF	: 20,
    GAME_FOOTER_TOP         : 766,
    GAME_VIEW_HEIGHT        : 620,
    GAME_JS_RAND_NUM        : 0,
	MESSAGE_SUCCESS			: 'SENT!  Thank you.',
	MESSAGE_CLOSE_WINDOW	: 'Please close this window',
    MESSAGE_OUTFIT_SAVE     : 'Your outfit has been saved!',
	MESSAGE_CLICK_ON_DESIGN	: 'Please click any design!',
	MESSAGE_DELETE_PRODUCED_DESIGN	: 'Are you sure you want to delete this produced design?',
	MESSAGE_PURCHASED_ITEM	: 'The item has been purchased!',
	MESSAGE_WEARING_OUTFIT	: 'You are now wearing this outfit!',
	MESSAGE_NO_CLOTHES		: 'You have no clothes to wear. Please go shopping now',
	MESSAGE_CANNOT_AFFORD	: 'You can not afford the item.',
	MESSAGE_ALREADY_OWN		: 'You already own this item in your closet!',
	MESSAGE_ITEM_NOT_IN_STOCK	: 'The item is not in stock.',
	MESSAGE_ITEM_NOT_EXISTS	: 'The item does not exist.',
	MESSAGE_INVALID_PAGE	: 'Invalid call to GAME.interface!',
	MESSAGE_LEAVING_GAME	: 'ARE YOU SURE YOU WANT TO LEAVE?\n\nClicking OK will end your Game Session.',
	MESSAGE_POPUP_WINDOW_WARNING	: 'In order for this game to function correctly, you need to <b>allow pop-up windows</b>.  Please change the setting in your browser.  Refresh this window after you have made the change.',
	MESSAGE_PROFILE_UPDATED	: '<div>Your profile has been updated!</div>',
	MESSAGE_BOOKMARK_REMOVED: 'Bookmark has been removed from your bookmark list',
	MESSAGE_FABRIC_SUCCESS	: 'Your fabric has been uploaded',
	MESSAGE_UPGRADE_MEMBERSHIP	: '<br />&nbsp;&nbsp;Sorry, you must be a VIP member to use this feature.<br />&nbsp;&nbsp;<a onclick="GAME.upgrade()" style="color:blue;">Click here to upgrade.',
	MESSAGE_NO_STORES		: 'Sorry, there are no stores in this neighborhood yet.  Please choose another neighborhood.',
	MESSAGE_END_STORES		: 'No more stores in this neighborhood.',
	MESSAGE_OWN_TRADEMARK	: 'You already trademarked this name.  Try something else.',
	MESSAGE_TRADEMARKED_DESIGN	: 'Sorry, this name is already trademarked.  Please try a different name.',
	MESSAGE_NON_UNIQUE_TRADEMARK	: 'This name was already chosen by a different designer but not trademarked.  You will not be the only person to have used this name.',
	MESSAGE_NO_MONEY_SAMPLE	: 'It looks like you can not afford to produce this design right now. This design will remain in your sampleroom until you have enough money to produce it.',
	MESSAGE_DIVA_SAVED		: 'Your Diva has been Saved!',
	MESSAGE_SEARCHBAR_TEXT	: 'Username/Email Address',
	IMAGE_LOADING_SPINNER	: '<img src="/images/loading.gif" />',
	ERROR_TRY_AGAIN			: 'Sorry, there was an error.  Please try again!',
    ERROR_FRIEND_EXISTS_IN_LIST : 'This user is already on your friends list',
    ERROR_FRIEND_NOT_EXISTS : 'User does not exist.',
	ERROR_SELECT_DESIGN		: 'Please select a design and try again!',
	ERROR_FILL_ALL_FIELDS	: 'Please fill out all fields',
    ERROR_EMPTY_USERNAME    : 'You must enter a username',
	ERROR_FILL_ALL_FIELDS_PASSWORD	: 'New and confirm passwords do not match',
	ERROR_NO_FILE_CHOSEN	: 'You must select a file to upload.',
    ERROR_GAME_FAIL         : 'Sorry but there was an error in the game.  Click the Refresh button to refresh the window.',
	ERROR_INCORRECT_FILE_TYPE	: 'The file must be an image of type jpg, png, or gif.',
	ERROR_FABRIC_FAILURE	: 'Sorry, there was a problem uploading the file.  Please try again.',	
	ERROR_SELECT_FACTORY	: 'You must select a factory!',
	ERROR_UNEXPECTED_PRICE	: 'Sorry, the price is either in the wrong format or priced too high!',
	ERROR_PRICE_OVER_ZERO	: 'Please enter a price greater than 0.00 for this design',
	ERROR_DESIGN_MISSING_NAME	: 'Please enter a name for your Design',
	ERROR_UNDER13_BLOG		: 'Sorry, but you need parental permission or to become a VIP in order to read or write in blogs.',
	ERROR_UNDER13_INVITE	: 'Sorry, but you need parental permission or to become a VIP in order to invite friends to the Fashion Fantasy Game.',
    CANNED_RESPONSES        : []
}

// Define GAME obj
var GAME = {
adRePoz: false,
dialogs: {},

$: function(id) {
	return YAHOO.util.Dom.get(id);
},
/**********************************************
 *
 *  getAssetFolder($id)
 *  
 *  Given an asset/rendered image id, will return the
 *  hashed folder it resides in as a string.
 *  
 *  Example:  
 *  
 *  getAssetFolder(123456);  ===> "34/56/"  
 *  
 ********************************************/         
getAssetFolder: function(id){
  var folder2 = id % 100;
  var tmp = Math.floor(id / 100);
  var folder1 = tmp % 100;
  
  folder2 = folder2.toString();
  folder1 = folder1.toString();
  if(folder2.length < 2) { 
    folder2 = "0" + folder2;
  }
  if(folder1.length < 2) {
    folder1 = "0" + folder1;
  }
    
  return folder1 + "/"  + folder2+  "/";
},
/**********************************************
 *
 *  getRandomNumber($type, $id, $size = '')
 *  
 *  Simply returns a random number between 10000 and 1
 *  
 ********************************************/     
getRandomNumber: function() {
    if (arguments.length > 0) {
        return Math.round(Math.random() * (10000 - 1) + 1);
    }
    return this.constants.GAME_JS_RAND_NUM;
},
/**********************************************
 *
 *  getAssetPath($type, $id, $size = '')
 *  
 *  Given an asset type, returns the path of 
 *  the image relative to the document root  
 *  
 *  type:  'rendered' or 'produced'
 *  size:  '' or 'thumb' or 'cropped'  
 *
 ********************************************/     
getAssetPath: function(type, id, size, stamp){  

  if (stamp == undefined) {
	stamp = this.getRandomNumber();
  }
  
  if (size == undefined) {
    size = '';
  }
  if(size != '') {
    size = "-" + size ;
  }
    
  if(type == 'produced' ){
     path = "/assets/produced_with_folders/" + this.getAssetFolder(id) + id + size + ".png?" + stamp;
  }else if(type == 'rendered' ){
//   path = "/assets/rendered_with_folders/" + this.getAssetFolder(id) + id + size + ".png?" + stamp; 
     path = "/assets/design.php?id=" + id + "&size=" + size.substr(1) + "&" + stamp; 
  }else{
     path = "/assets/"+ type+ "/" + this.getAssetFolder(id) + id + size + ".png?" + stamp;
  }
  return path;
}
,

ticker: function(){
	setInterval(this.processTicker, 300000);
	/*if(!readCookie('PHPSESSID')) {
		//alert('session invalid');
		//this.end();
	}
	return;
	**/
},

processTicker: function() {
	var url = "online_users.php?arg=" + GAME.constants.GAME_JS_RAND_NUM;
	var me = this;
	var data = "";
	
	var cb = {
		success: function(d){
			data = GAME.evalResponse(d.responseText);
			
			GAME.buddylist.processTicker(data.friends);
			GAME.messages.processTicker(data.unread);
			
			if ( GAME.bank.processTicker(data.balance) == 1 ) {
				soundManager.play('money');
			}
		},
		failure: function(d){}
	};				

	YAHOO.util.Connect.asyncRequest('GET', url, cb);
},

showToolTips: function() {

	var ToolTip=YAHOO.widget.Tooltip;
		 var id_names = [
						 "profile_btn_pop",
						 "closet_btn_pop",
						 "showroom_btn_pop",
						 "travel_btn_pop",
						 "go_shopping_btn_pop",
						 "sell_designs_btn_pop",
						 "meet_designers_btn_pop",
						 "cafe_btn_pop",
						 "advertise_btn_pop",
						 "rankings_btn_pop",
						 "blog_btn_pop",
						 "message_btn_pop",
						 "bank_btn_pop",
						 "make_a_new_design_btn_pop",
						 "sampleroom_btn_pop",
						 "fashion-meter",
						 "header_balance_pop",
						 "header_stripe_home"
						 ];
		 
		 var id_refs = new Array(id_names.length);

		for (var i=0;i<id_names.length;i++) {
			id_refs[i] = document.getElementById(id_names[i]);
		}
		
   		YAHOO.util.Event.onDOMReady(function() {
 		  	// tooltips
			tt0 = new ToolTip("tt", { context:id_refs } ); 			
	});
	
},

home: function(){
	this.adRePoz = true;	
	var board_img = $('middle_board_panel'),
		board_text = $('middle_board_panel_text'),
		path = false;

    this.process_history({'id':0,'where':'home'});
    this.trackPageView("/panels/board.php");	
    paneSwitch('A');		
		
	if (this.home.toggle) {
		//board_text.style.display = 'none'
		path = '/images/banners/VIP_page_2.png';
		//board_img.style.cursor = 'hand';
		//board_img.style.cursor = 'pointer';
		/*board_img.onclick = function() {
			this.upgrade()
		};*/
        logRequest();
	}
	else {
		//board_text.style.display = 'block';
		path = this.home.dynamic_board[0] + this.location + this.home.dynamic_board[1];
		//board_img.style.cursor = '';
		//board_img.onclick = '';
		/*
		YAHOO.util.Connect.asyncRequest('GET', 
										'api.php?action=get-board-text', 
										{ 	success: function(d){ board_text.innerHTML = d.responseText; },
											failure: function(d){ board_text.innerHTML = ""; }
										},
										null);*/
	}
	
	//board_img.style.backgroundImage = 'url(' + path + ")";

	this.home.toggle = (this.home.toggle ? false : true);

	// check for diva change
	if (this.player.diva.doDivaUpdate()) {
		try {
			var diva = $('board_diva');
			diva.src = this.getPlayerDiva('closet');
		}
		catch (e) {
		}
	}

	// check for outfit change
	if (this.player.outfitChange == true) {
		try {
			var outfit = $('board_outfit'),
				garment = null,
				node = YAHOO.util.Selector.query('img.imgnone', outfit, true); 
			
			garment = node.src;
			this.player.outfitChange = false;
			node.src = garment + this.date.getTime();
		}
		catch(e){}
	}
},
addHeaderHandlers: function() {
	// configure header button handlers
	try {
		$('header_search_btn').onclick = function() {
			var val = $('header_searchbar');
			if (val.value == GAME.constants.MESSAGE_SEARCHBAR_TEXT) {
				GAME.alert('Please enter a username or email address.', 'Oops');
			}
			else {
				GAME.findUserPage(val.value);
			}
		}
	}
	catch (e) {}
		
	var header_searchbar = {}
	
	try {
		header_searchbar = $('header_searchbar');
	}
	catch (e) {	}

	header_searchbar.value = GAME.constants.MESSAGE_SEARCHBAR_TEXT;
	header_searchbar.style.color = '#C0C0C0';
	header_searchbar.onclick = function(e) {			
		if (this.value == GAME.constants.MESSAGE_SEARCHBAR_TEXT) {
			this.value = "";
			this.style.color = 'black';
		}
	}

	header_searchbar.onblur = function(e) {
		if (this.value == "") {
			this.value = GAME.constants.MESSAGE_SEARCHBAR_TEXT;
			this.style.color = '#C0C0C0';
			return;
		}
	}

	header_searchbar.onkeyup = function(e) {
		var characterCode; // literal character code will be stored in this variable
		
		// check if window is open
		if (typeof(GAME.dialogs['findUser-dialog']) !== "undefined") {
			GAME.alert('Please use the search dialog', 'Oops');
			this.value = GAME.constants.MESSAGE_SEARCHBAR_TEXT;
			this.style.color = '#C0C0C0';
			return;
		}

		if (this.value == "") {
			this.value = GAME.constants.MESSAGE_SEARCHBAR_TEXT;
			this.style.color = '#C0C0C0';
			return;
		}
		
		if (e && e.which) {
			//if which property of event object is supported (NN4)
			e = e
			characterCode = e.which //character code is contained in NN4's which property
		}
		else {
			e = event
			characterCode = e.keyCode //character code is contained in IE's keyCode property
		}
		
		if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
			GAME.findUserPage($('header_searchbar').value); //submit the form
			this.value = GAME.constants.MESSAGE_SEARCHBAR_TEXT;
			this.style.color = '#C0C0C0';
			return false;
		}
		else {
			return true;
		}
	}

	$('header_stripe_back').onclick = function() {
		GAME.process_history();
	}
	$('header_stripe_home').onclick = function() {
		GAME.home();
	}
	$('header_stripe_email').onclick = function() {
		GAME.mailBox();
	}
	$('header_stripe_fbz').onclick = function() {
		GAME.thebank();
	}
	$('header_stripe_friends').onclick = function() {
		GAME.friendsList();
	}
	$('header_stripe_faves').onclick = function() {
		GAME.bookmarkList();
	}
},

popupsNotAllowed: function(diag) {
	var btns = [{
		text:"Ok",
		handler:function() {
			this.destroy();
			GAME.dialog(diag);
		},
		isDefault:true
	}];
	GAME.alert(GAME.constants.MESSAGE_POPUP_WINDOW_WARNING, 'Warning', btns);
},

getPlayerDiva: function(type) {
	var sDiva = "",
		divaAttrs = null;
	
	sDiva = "/images/divas/";
	divaAttrs = this.player.diva.getDiva();
	
	sDiva += "skin" + divaAttrs['skin']
			+ "_eyes" + divaAttrs['eyes']
			+ "_hair" + divaAttrs['hair'];
	
	if (typeof(type) == "undefined") {
		type = "";
	}
	
	switch(type) {
		case('thumb'):
			sDiva += "_thumb";
			break;
		case('closet'):
			sDiva += "_closet";
			break;		
		default:
			sDiva += "_closet";
			break;
	}
	
	sDiva += ".png";
	
	return sDiva;
},

thebank: function(){

    this.trackPageView("/data/bank/main.php");
		
	this.process_history({'id':0,'where':'thebank'});
        
	GAME.loadPanel('data/bank/main.php', 'I', function() { GAME.displayAd('mediumRectangle'); });
},

getBalance: function(){
	
	return this.bank.balance;
},

exit: function(){

	GAME.dialog({
		id: 'logout-confirm',
		modal: true,
		body: '<div style="height: 70px;padding-top: 30px;">End Game for today ?</div>',
		title: 'Confirm Logout',
		xy: [260, 230],
		buttons: [
			{ text: 'Yes, logout', handler: function(){ GAME.end(); }, isDefault: false },
			{ text: 'No, continue Playing', handler: function(){ this.destroy(); }, isDefault: false }
		]
	});
},

end: function(){
	window.onbeforeunload = null;
    
    try {
        chat_window.close();
    }
    catch(e) {}
	window.location = 'logout.php';
},

upgrade: function(){
	//GAME.allowNav();
// -- it is counted inside...    this.trackPageView("/data/bank/upgrade.php");

	var w = window.open('https://'+window.location.host+'/data/bank/upgrade.php','bucks3','resizable=yes,width=750,height=651,scrollbars=yes');
},

cancelAcct: function(link, w, h){
	var myaccount = window.open(link, 'My_Account', 'width='+w+',height='+h+',resizable=0,scrollbars=1');
},

findUserPage: function(arg) {
	YAHOO.initial_load.container.wait.show();
	var cb = function(d){
		YAHOO.initial_load.container.wait.hide();
		var m = GAME.dialog({ 
			id:'findUser-dialog',
			title: 'Find User',			
			body: d,
			fixedcenter: false,   
			visible: true,  
			zIndex: 90,
			xy: [100, 160],
			draggable: true, 
			constraintoviewport: true,
			width: '505px',
			modal: false,
			close:false,
			buttons: [ 
				{ text:"Search", handler: function(){ GAME.findUsers(); }, isDefault:true },
				{ text:"Cancel", handler: function(){ this.destroy(); GAME.findUsers.cache=0; }, isDefault:false } 
			],
			deleteOp: true
		});
        
        m.validate = function() {
            var data = GAME.dialogs['findUser-dialog'].getData();
            if (data.text.length < 4) {
                GAME.alert('Sorry, but you must enter more than 3 characters.');
                return false;
            }
            
            return true;
        }
		
		if (typeof(arg) !== "undefined") {
			$('text').value = arg;
			GAME.findUsers.action = 'users';
			GAME.findUsers();
		}
	}
	GAME.getPage("data/findUsers.php", cb);
	return;
},

inviteUser: function(email) {
	var div = document.getElementById('fillMe');
	var post = 'email=' + email;

	var cb = {
		success: function(d){
			div.innerHTML = GAME.constants.MESSAGE_SUCCESS;
		},
		failure: function(d){}
	};
	YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=invite-new-user', cb, post);
},

inviteUsersPage: function() {
	if (GAME.player.getPlayerStatus() === 0) {
		this.inviteUsersPage = function() {
			return this.alert(GAME.constants.ERROR_UNDER13_INVITE, 'Oops');
		}
		this.inviteUsersPage();
		return;
	}
	YAHOO.initial_load.container.wait.show();
	var cb = function(d){
		YAHOO.initial_load.container.wait.hide();

		var m = GAME.dialog({ 
			id:'inviteUsers-dialog',
			title: 'Invite Users',			
			body: d,
			fixedcenter: true,   
			visible: true,  
			zIndex: 90,
			xy: [80, 120],
			draggable: true, 
			close: false,
			constraintoviewport: true,
			width: '550px',
			modal: true,
			buttons: [ 
				{ text:"Send", handler: function() {GAME.inviteUsers();}, isDefault:true },
				{ text:"Cancel", handler: function(){ this.destroy(); }, isDefault:false } 
			],
			deleteOp: true
		});
	}
	GAME.getPage("data/inviteUsers.php", cb);
	return;	
},

inviteUsers: function(emails) {
	var div = document.getElementById('fillMe');
	var data = GAME.dialogs['inviteUsers-dialog'].getData();
	var post = '';
	YAHOO.initial_load.container.wait.show();
	
	for(x in data){
		if(post.length>0) post += '&';		
		post += encodeURIComponent(x) + '=' + encodeURIComponent(data[x]) + '';
	}

	if(post==''){
		GAME.alert(GAME.constants.MESSAGE_CLOSE_WINDOW);
		return;
	}

	var cb = {
		success: function(d){
			YAHOO.initial_load.container.wait.hide();
			GAME.dialogs['inviteUsers-dialog'].cancel();
			GAME.alert(GAME.constants.MESSAGE_SUCCESS);
		},
		failure: function(d){
			GAME.alert(GAME.constants.ERROR_TRY_AGAIN);
		}
	};

	YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=invite-multiple-users', cb, post);	
},

findUsers: function() {
	var f = GAME.dialogs['findUser-dialog'].form;
	var data = GAME.dialogs['findUser-dialog'].getData();
	var reference = GAME.dialogs['findUser-dialog'];
	var filltable = $('fillMe');
	
    if (data.text.length < 4) {
        GAME.alert('Sorry, but you must enter more than 3 characters.');
        return;
    }
    
	var lastRow = filltable.rows.length;		
	for (var x=lastRow;x>0;x--) {
		filltable.deleteRow(x-1);
	}
	
	var post = '';
	for (x in data) {
		if (post.length>0) {
			post += '&';
		}
		post += x + '=' + encodeURIComponent(data[x]) + '';
	}
    
    post += '&param='+GAME.findUsers.action;
	
	if (arguments.length > 0) {
		post += '&start='+arguments[0];
	}
	
	$('search_users_loading').style.display='block';
	
	var cb = {
		success: function(d){
			var messages = [],
			nodeText = "";	

			try { 
				messages = YAHOO.lang.JSON.parse(d.responseText); 
			} 
			catch (x) { 
				GAME.alert(GAME.constants.ERROR_TRY_AGAIN); 
				return; 
			} 
			
			count = messages.shift();
			$('search_users_loading').style.display='none';

			if ( messages.length==0 || messages[0]==undefined || messages[0]==null || messages[0].id==0 ) {
				var tr = document.createElement('TR');
				var t1 = document.createElement('TD');				
				t1.setAttribute('align','center');	
				t1.setAttribute('colspan','2');			
				t1.setAttribute('style', 'color:black');
				
				
				var message_text = document.createTextNode( 'Sorry, no results found.' ); 
				t1.appendChild(message_text);
				tr.appendChild(t1);
				filltable.appendChild(tr); 
			}
			else {
                for (var i = 0, len = messages.length; i < len; ++i) {   
                    var tr = document.createElement('tr');
                    var a = document.createElement('a');
                    var br = document.createElement('br');
                    var t = document.createElement('td');
                    var m = messages[i]; 
                    var user_type = (m.type == "" 
                                    ? (m.store_id == ""
                                        ? GAME.constants.DESIGNER
                                        : GAME.constants.STOREOWNER)
                                    : (m.type == GAME.constants.DESIGNER
                                        ? 1
                                        : 2));
					var tr1 = tr.cloneNode(false);
					var t1 = t.cloneNode(false);
					var a1 = a.cloneNode(false);
					var message_text = document.createTextNode( m.user ); 
					var message_text1 = document.createTextNode( nodeText );
					var message_text2 = document.createTextNode( 'View My Profile!   ' );
					t.setAttribute('align','left');
					t.setAttribute('style', 'color:black');
					t.appendChild(document.createTextNode("User: "));
					t.appendChild(message_text);
                    if ( m.thing_name != "") {
                        t.appendChild(document.createElement('br'));
                        _name = (user_type==1?"Design ":"Store ") + "Name :";
                        t.appendChild(document.createTextNode( _name ));        
                        t.appendChild(document.createTextNode( m.thing_name ));
                    }
					tr1.appendChild(t);
					
					//a.setAttribute('onclick','GAME.viewProfile("'+m.id+'")');
					YAHOO.util.Event.on(a, 'click', function(e, id){ reference.destroy(); GAME.viewProfile(id); }, m.id);
					a.appendChild(message_text2); 					

					t1.setAttribute('align','left');
   
                    if (user_type == 2) {
                        YAHOO.util.Event.on(a1, 'click', function(e, params){ reference.destroy(); GAME.browseStore(params.arg1); }, {"arg1":(GAME.findUsers.action === "stores"?m.place_id:m.store_id)});
                        message_text1 = document.createTextNode("View My Store!");
					}
                    else if (user_type == 1) {
                        YAHOO.util.Event.on(a1, 
                                            'click', 
                                            function(e, params){
                                                reference.destroy(); 
                                                GAME.viewShowroom(params.arg1,params.arg2); 
                                            }, 
                                            {"arg1":m.id, "arg2":m.design_id}
                        );
                        message_text1 = document.createTextNode("View My Showroom!");
					}
					else {
						YAHOO.util.Event.on(a1, 'click', function(e, id){ GAME.viewShowroom(id); }, m.id);
					}

					a1.appendChild(message_text1); 
					t1.appendChild(a); 	
					t1.appendChild(br);
					t1.appendChild(a1); 				
					tr1.appendChild(t1);
					
					filltable.appendChild(tr1); 					
				} 

				if (count.count != "ignore") {
					try {
						var num_pages = Math.ceil(parseInt(count.count) / 10);
						var pages = '';
						var tr_count = tr1.cloneNode(false);
						var t1_count = t.cloneNode(false);				
						t1_count.setAttribute('align','center');	
						t1_count.setAttribute('colspan','2');			
						t1_count.setAttribute('style', 'color:black');

						for(var i=1;i<=num_pages;i++) {
							pages += '<a style="color:blue;text-decoration:underline;" onclick="GAME.findUsers('+(i-1)+');" >' + i +'</a>' + '&nbsp;&nbsp;';
						}
										
						t1_count.innerHTML = pages
						tr_count.appendChild(t1_count);
						GAME.findUsers.cache=tr_count;
					}
					catch(e) {}
				}
		
				filltable.appendChild(GAME.findUsers.cache.cloneNode(true)); 							
			}
		},
		failure: function(d){
			GAME.alert(GAME.constants.ERROR_TRY_AGAIN,'Oops'); 
		}
	};
	
	YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=find-member', cb, post);
},

funk: function(page, type, id) {
	GAME.process_history({'id':0,'where':'meetdesigners'});
	GAME.trackPageView(page+'&type='+type+'&id='+id);

	var obj = this;
	
	var cb = function(d) {
		$('designers_result').innerHTML = d;
	}
	
	if (id == undefined) {
		if (GAME.designers_current_city != undefined) {
			id = GAME.designers_current_city;
		}
		else {
			id = $('default_location').value;
		}
	}
	
	if (GAME.designers_current_tab == undefined) GAME.designers_current_tab = 'popular';
	$('tabs_'+GAME.designers_current_tab).src = '/images/designers/tabs-'+GAME.designers_current_tab+'-s.png';
	GAME.designers_current_tab = type;
	GAME.designers_switch_tab(type, 'toggle');
	GAME.getPage(page+'&type='+GAME.designers_current_tab+'&id='+id, cb);
	
},

funk_city: function(page, id) {
	GAME.designers_current_city = id;
	if (GAME.designers_current_tab == undefined) GAME.designers_current_tab = 'popular';
	GAME.funk(page, GAME.designers_current_tab, id);
	
},

designers_switch_tab: function(type, action) {
	
	if (GAME.designers_current_tab == undefined) GAME.designers_current_tab = 'popular';
	
	switch(type) {
		case 'popular':
			if (action == 'toggle') {
				$('tabs_popular').src = '/images/designers/tabs-popular.png';
			}
			if (action == 'over' && GAME.designers_current_tab != 'popular') {
				$('tabs_popular').src = '/images/designers/tabs-popular.png';
			}
			if (action == 'out' && GAME.designers_current_tab != 'popular') {
				$('tabs_popular').src = '/images/designers/tabs-popular-s.png';
			}
			
		break;
		case 'new':
			if (action == 'toggle') {
				$('tabs_new').src = '/images/designers/tabs-new.png';
			}
			if (action == 'over' && GAME.designers_current_tab != 'new') {
				$('tabs_new').src = '/images/designers/tabs-new.png';
			}
			if (action == 'out' && GAME.designers_current_tab != 'new') {
				$('tabs_new').src = '/images/designers/tabs-new-s.png';
			}
		break;
		case 'neighborhood':
			if (action == 'toggle') {
				$('tabs_neighborhood').src = '/images/designers/tabs-neighborhood.png';
			}
			if (action == 'over' && GAME.designers_current_tab != 'neighborhood') {
				$('tabs_neighborhood').src = '/images/designers/tabs-neighborhood.png';
			}
			if (action == 'out' && GAME.designers_current_tab != 'neighborhood') {
				$('tabs_neighborhood').src = '/images/designers/tabs-neighborhood-s.png';
			}
		break;
		case 'tags':
			if (action == 'toggle') {
				$('tabs_tags').src = '/images/designers/tabs-tags.png';
			}
			if (action == 'over' && GAME.designers_current_tab != 'tags') {
				$('tabs_tags').src = '/images/designers/tabs-tags.png';
			}
			if (action == 'out' && GAME.designers_current_tab != 'tags') {
				$('tabs_tags').src = '/images/designers/tabs-tags-s.png';
			}
		break;		
		case 'online':
			if (action == 'toggle') {
				$('tabs_online').src = '/images/designers/tabs-online.png';
			}
			if (action == 'over' && GAME.designers_current_tab != 'online') {
				$('tabs_online').src = '/images/designers/tabs-online.png';
			}
			if (action == 'out' && GAME.designers_current_tab != 'online') {
				$('tabs_online').src = '/images/designers/tabs-online-s.png';
			}
		break;		
		case 'totals':
			if (action == 'toggle') {
				$('tabs_totals').src = '/images/designers/tabs-totals.png';
			}
			if (action == 'over' && GAME.designers_current_tab != 'totals') {
				$('tabs_totals').src = '/images/designers/tabs-totals.png';
			}
			if (action == 'out' && GAME.designers_current_tab != 'totals') {
				$('tabs_totals').src = '/images/designers/tabs-totals-s.png';
			}
		break;
	}
	
	
},

showDesignerSamples: function(id){
	//alert('showing designer samples for: ' + id);
	this.loadContent('designer/samples.php?id=' + id, 'designer-samples');
},

assignChecklistHandlers: function(args) {
	for (var i = 0, len = args.length; i < len; i++) {
		switch (args[i]) {
			case("edit_profile"):
				try {
					$('edit_profile_func').onclick = function() {
						GAME.editProfile();
					}
				}
				catch (e) {}
			break;
			case("validate_email"):
				try {
					$('validate_email_func').onclick = function() {
						GAME.editAccount();
					}
				} catch (e) {}
			break;
			case("rent_space"):
				try {
					$('rent_space_func').onclick = function() {
						GAME.neighborhoodList();
					}
				} catch (e) {}
			break;
			case("design_logo"):
				try {
					$('design_logo_func').onclick = function() {
						GAME.editLogo();
					}
				} catch (e) {}
			break;
			case("make_design_or_store"):
				try {
					$('make_design_or_store_func').onclick = function() {
						if (GAME.player.type == GAME.constants.DESIGNER) {
							GAME.newDesign();
						}
						else {
							GAME.redesignStore();
						}
					}
				} catch (e) {}
			break;
			case("design_diva"):
				try {
					$('design_diva_func').onclick = function() {
						GAME.divaPage();
					}
				} catch (e) {}
			break;
			case("go_shopping"):
				try {
					$('go_shopping_func').onclick = function() {
						GAME.goShopping();
					}
				} catch (e) {}
			break;
			case("get_dressed"):
				try {
					$('get_dressed_func').onclick = function() {
						GAME.closet();
					}
				} catch (e) {}
			break;
			case("edit_profile"):
				try {
					$('edit_profile_func').onclick = function() {
						GAME.editProfile();
					}
				} catch (e) {}
			break;
			case("edit_blog"):
				try {
					$('edit_blog_func').onclick = function() {
						GAME.fashionLog();
					}
				} catch (e) {}
			break;
			case("click_help"):
				try {
					$('click_help_func').onclick = function() {
						GAME.help(false);
					}
				} catch (e) {}
			break;		
		}
	}
},

processChecklist: function(type) {
	/****
		This function processes the game checklist that a user must complete
		This function corresponds to the PHP method
		environment->processChecklist() as well as several methods in the JS
		player class.
	**/
	var elem = null,
		url = "",
		completed = false;
	
	if (type === false) {
		// take away 10FBz!
		YAHOO.util.Connect.asyncRequest('GET', 'api.php?action=checklist-minus', {
				success: function(d) {
					GAME.alert('10FBz was just removed from your bank account.', 'Message');
				},
				failure: function(d) {}
			}, null);
		return;
	}
	
	if (GAME.player.isChecklistComplete()) {
		return;
	}
	
	if (GAME.player.getChecklistValue(type) === true) {
		return;
	}
	
	// show the checklist if hidden
	GAME.checklist.show();
	
	url = "api.php?action=checklist";
	completed = false;
		
	GAME.player.setChecklistValue(type);
	GAME.player.processChecklist(GAME.checklist);

	try {
		elem = $(type);
		YAHOO.util.Dom.removeClass(elem, 'checklist_checkbox_unchecked');
		YAHOO.util.Dom.addClass(elem, 'checklist_checkbox_checked');
	}
	catch (e) {}
	
	if (type == "click_help") {
		url += "&arg=help";
	}

	YAHOO.util.Connect.asyncRequest('GET', url, {
			success: function(d) {
				GAME.processTicker();
			},
			failure: function(d) {}
		}, null);
	
},

editLogo: function(){
	this.process_history({'id':0,'where':'editLogo'});

	if(this.logoEditor==undefined) {
		this.logoEditor = new logoEditor();
	}
        GAME.wideAdPoz();
	GAME.loadPanel('logo/logo.html', 'J', function(){ });
}, 

editLogoConfirm: function(){
		// IE hack to override onbeforeunload event
		GAME.allowNav();

		GAME.processChecklist("design_logo");
		
		var m = GAME.dialog({
               id:'editLogoConfirm-dialog',
               title: 'Confrim',
               body: 'Congrats! Your logo has been saved!<br /><a style="color:blue; text-decoration: underline;" href="javascript: GAME.process_history(); GAME.dialogs[\'editLogoConfirm-dialog\'].destroy();">Click here</a> to go back to your profile page.',
               fixedcenter: true,
               visible: true,
               modal: false,
               zIndex: 150,
               //xy: [150, 280],
               draggable: true,
               constraintoviewport: true,
               width: '350px',
               buttons: [{
					text: "Close",
					handler: function() {
						this.destroy();
					},
					isDefault: true
				}]
		});
},

fashionShow: function(){
	notice('Not Yet...');	
},

clearPanel: function(which){
	$(which).innerHTML = '';	
},

evalResponse: function(responseText){
	var x = eval(responseText);
	return x[0];
},

interfac: function(ob){
	
	if(ob.panel==undefined||ob.path==undefined){
		GAME.alert(GAME.MESSAGE_INVALID_PAGE);
		return;
	}
	$(ob.panel).innerHTML = GAME.constants.IMAGE_LOADING_SPINNER;
	explain = false;
	var reqs = new getXMXHTTPRequest();
	reqs.open("GET", xmlPath, true);
	reqs.onreadystatechange = function(){
		if(reqs.readyState ==4){
			switch(reqs.status){
				case(404):	notice(xmlPath +'<hr/>does not exist');
							//alert(xmlPath +'\ndoes not exist: \n\n' + xmlPath);
				break;
				case(200):	if(explain) alert('simulated loading delay...\n\nYou should see a timed loading pop-up');
							//var response = parseDOM(reqs.responseText);
							//GAME.messages.loadMessages
							$(panel).innerHTML = reqs.responseText;
							if(ob.oncomplete!=undefined) ob.oncomplete();
				default:
			}
		} else {
			//alert('Problem: XMP HTTPRequest status: ' + req.status);
		}
	}
	reqs.send(null);
},

allowNav: function(){
	window.onbeforeunload = function(){};
},

preventNav: function(){
	window.onbeforeunload = function(){
        try {
            chat_window.close();
        }
        catch(e) {}
		return GAME.constants.MESSAGE_LEAVING_GAME;
	}
},

openChatWindow: function() {
	var url="";
	var cb=0;
	if ( arguments.length > 0 ) {
		url="cafe/chatroom.php?id="+arguments[0];
	}
	else {
		url="cafe/chat.php";
	}
    
// -- counted directly    this.trackPageView("/cafe/chat.php");

	 chat_window = window.open(url,"chat_window","menubar=0,resizable=0,width=680,height=540,resizable=1");
},

start: function() {
	/* Module definition */
	//	this.modules = Array();
	//	this.modules['buddylist'] = new buddylist();
	//	this.modules['bank'] = new bank();
	//	this.modules['store'] = new store();
	//	this.modules['player'] = new player();
	//	this.modules['community'] = new community();
	//	this.modules['messages'] = new messages();
	//	this.store = this.modules['store'];
	//	this.player = this.modules['player'];
	//	this.community = this.modules['community'];
	//	this.bank = this.modules['bank'];
	//	this.buddylist = this.modules['buddylist'];
	//	this.messages = this.modules['messages'];
	
	this.checklist = new YAHOO.widget.Panel("game_checklist", {
		width:		"330px",
		zIndex:		9000,
		visible:	false,
		constraintoviewport:true
	});

	this.checklist.render();
	this.checklist.show();
	try {
		$('checklist_skip').onclick = (function() {
			var cl = arguments[0];
			return function() {
				cl.hide();
				GAME.processChecklist(false);
			}
		})(this.checklist);
	}
	catch (e) {}

	this.bank = new bank();
	this.buddylist = new buddylist();
	//this.buddylist.set_ref_to_counter_el('friends_count');
	this.messages = new messages();
	this.store = new store();
	this.player = new player(this);
	this.date = new Date();
	this.history = new HistoryQueue({
		'size': 20,
		'initialEntry': {
			'id': 0,
			'where': 'home'
		},
		'lastEntry': {
			'id': 0,
			'where': 'home'
		},
		'initialEntry': {
			'id': 0,
			'where': 'home'
		}
	});

	this.initDialogs();
	this.constants = constants;
    this.constants.GAME_JS_RAND_NUM = this.getRandomNumber(true);
	this.location = false;
	this.openPanel = false;
	this.shopping = false;
	this.planeTicketPrice = 400.00;
	this.designMode = false;
	this.autoCheckMessages = 1;	
	this.autoCheckBalance = 1;
	this.mode = 1;
	this.findUsers.cache = 0;
	this.home.dynamic_board = [];
	this.home.toggle = false;
	this.ticker = GAME.ticker();
},

profilePage: function(id) {
	var sURL = 'api.php?action=is-profile-configured&id='+id;

	if (this.player.profileIsSet == 0) {
		// if configured, view it
		// else edit it
		var cb = {
			success: function(d) {
				if (parseInt(d.responseText) >= 1) {
					GAME.viewProfile(d.responseText);
					GAME.player.profileIsSet = 1;
				}
				else {
                    GAME.editProfile();
				}
			},
			failure: function(d) {}
		};
		
		YAHOO.util.Connect.asyncRequest('GET', sURL, cb, null);
	}
	else {
		GAME.viewProfile(GAME.player.uid);
	}
},

editProfile: function() {
    this.trackPageView("/profile/editProfile.php");
	// history missing...
	GAME.loadPanel('profile/editProfile.php', 'Q', function() {
		GAME.profileEditor = false;
        GAME.profileEditor = new ProfileEditor(GAME);
		
		var tabView = new YAHOO.widget.TabView('edit-profile-tabs');
	});	
},

viewProfile: function(id) {

    if (!this.IsNumeric(id)) {
        return;
    }

    // track history
    this.process_history({'id':id,'where':'profile'});
    
    //track pageview
    this.trackPageView("/community/profilePage.php");

    var slidedown = function() {
        $('game-footer').style.top = '1200px';
        $('V').style.height = '1100px';
        $('V').style.marginLeft = '-10px';
        var anim = new YAHOO.util.Anim('game-view', {height:{to:1049}}, 1, YAHOO.util.Easing.easeOut);
        anim.animate();        
    }

    GAME.loadPanel('community/profilePage2.php?id='+id, 'V', slidedown);
},

editAccount: function() {
	GAME.adRePoz = true;
	$url="/registration/editAccount.php";
    this.trackPageView($url);
    this.process_history({'id':0,'where':'editAccount'});
	GAME.loadPanel($url, 'MYACCOUNT', function() {});	
},

resizeStyleImg: function(type, file, model) {
    var body = '<div style="position:relative;width:220px;height:480px;"><img src="/assets/models/model'
                + model
                + '_large.png" /><img src='
                + file
                + ' alt="Clothing" style="position:absolute;top:0px;left:0px"/></div>'
    
    switch(type) {
            case('grow'):
                if (GAME.dialogs['profile-clothes-dialog'] !== undefined) {
                    GAME.dialogs['profile-clothes-dialog'].setBody(body);
                    GAME.dialogs['profile-clothes-dialog'].show();
                }
                else {
                    var m = GAME.dialog({ 
            			id:'profile-clothes-dialog',
            			title: 'Clothing Zoom',			
            			body: body,
            			fixedcenter: false,   
            			visible: true,  
            			zIndex: 90,
            			xy: [80, 120],
            			draggable: true, 
            			constraintoviewport: false,
            			width: '220px',
            			modal: false,
            			buttons: [ 
            				{ text:"Close", handler: function(){ this.destroy(); }, isDefault:false } 
            			],
            			deleteOp:true
                    });
                }
            break;
        case('shrink'):
        default:
            if (GAME.dialogs['profile-clothes-dialog'] !== undefined) {
                GAME.dialogs['profile-clothes-dialog'].hide();
            }
            break;
    }    
},

saveProfile: function() {
	var div = document.getElementById('status');
	
	var temp = new Array();
	var p = "&";
	var j;
	
	YAHOO.initial_load.container.wait.show();

	profiles_data = document.profiles.elements;

	for(j=0; j<profiles_data.length; j++) {
	    // was: for(i in documents.profiles)
		// safari fix: safari DOM does not have document.<formname>.<inputname>
		// instead, use document.<formname>.<elements>[numericalid].name
	    i = profiles_data[j].name;
	    i = (i ? i : '');
	    // end of fix
		if (i.indexOf("pf__") != -1) {
			temp = i.split("pf__");
			p += encodeURIComponent(temp[1]) + "=" + encodeURIComponent(profiles_data[i].value) + "" + "&";
		}
	}
	
	post = p.substring(0,p.length-1);

	var cb = {
		success: function(d){
			// mysql if we user update and then track affected rows, we will get 0 if nothing has changed....
			var json = eval('(' + d.responseText + ')'),
				is_profile_updated = json['is_profile_updated'],
				balance = json['balance'];
			
			GAME.processChecklist("edit_profile");
			
			if(is_profile_updated){
				msg = GAME.constants.MESSAGE_PROFILE_UPDATED;
			}
			if(balance != '0'){
				msg += "<div>Thank you for updating all your profile.</div>" +
							 "<div><b>Free 200 FBz</b> has been deposited to your account!</div>" + 
							 "<div>Your balance is now: <b>" + balance + " FBz</b></div>";
			}			
			GAME.alert(msg);
			YAHOO.initial_load.container.wait.hide();			
		},
		failure: function(d){
			YAHOO.initial_load.container.wait.hide();						
			GAME.alert(GAME.constants.ERROR_TRY_AGAIN);
		}
	};
	YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=save-profile', cb, post);
},

divaPage: function() {
	GAME.player.diva.divaPage('closet');
},

upgradeDialog: function() {
	var cb = function(d){
		var m = GAME.dialog({ 
			id:'upgrade-dialog',
			title: 'Upgrade Now?',			
			body: d,
			fixedcenter: true,   
			visible: true,  
			zIndex: 90,
			xy: [80, 120],
			draggable: true, 
			constraintoviewport: true,
			width: '440px',
			modal: true,
			buttons: [ 
				{ text:"Join Now", handler: function(){ this.destroy(); GAME.upgrade() }, isDefault:false },
				{ text:"Cancel", handler: function(){ this.destroy(); }, isDefault:false } 
			],
			deleteOp:true
		});
		
		m.callback = {
			success: function(d){
			},
			failure: function(d){
			}
		}
	}
	GAME.getPage("data/upgrade.php", cb);	
},

setFashionMeter: function(s) {
	var state;
	
	if ( typeof(s) != "string" ) {
		state = String(s);
	}
	else {
		state = s;	
	}	
		
	var image_path = "/images/meter/meter";

	switch(state) {
		case("1"):
			image_path += "1.png";
		break;
		case("2"):
			image_path += "2.png";
		break;
		case("3"):
			image_path += "3.png";
		break;
		case("4"):
			image_path += "4.png";
		break;
		case("5"):
			image_path += "5.png";
		break;
		default:
			image_path += "1.png";
		break;		
	}
	
	$("fashion-meter").src = image_path;
},

updateFashionMeter: function() {
	this.player.shopState = 1;
},

toggle_image: function(id, img) {	
	$(id).src = img;
},

requestPlayerData: function(type) {

	switch(type) {
	
	case("friends"):
		if ( document.getElementById('online-list-box').style.display != '' ) {
			GAME.getOnlineUsers();
			document.getElementById('online-container').style.borderTopColor='#000';
			document.getElementById('online-container').style.borderLeftColor='#000';
			document.getElementById('online-container').style.borderRightColor='#000';
		}
		else {
			document.getElementById('online-container').style.borderColor='#a9a9a9';
		}
		
		this.buddylist.ticker();
		toggle('online-list-box');
		break;
	case("money"):
		var url = "data/bank/api-min.php?action=curr-balance";
		var cb = {
		success: function(d){
			if ( GAME.bank.processTicker(d.responseText) == 1 ) 
				soundManager.play('money');
		},
		failure: function(d){}
		};				
		YAHOO.util.Connect.asyncRequest('GET', url, cb);
		break;
	defatult:
		break;
	}
},

loadDesigners: function(page){
	
	var id = 'designers-browser';
	var obj = this;
	
	$('designers-browser').innerHTML = GAME.constants.IMAGE_LOADING_SPINNER + '<br />Loading...';
	
	if(page!=undefined) {
		if(page<0) page = 0;
		obj.page = page;
	} else obj.page = 0;
	
	var cb = function(d){
		if(d==-1) {
			obj.page = obj.page-1;
			$('designers-browser').innerHTML = "";

			return;
		} 
		$('designers-browser').innerHTML = d;
	}
	GAME.getPage('data/designers.php?start=' +obj.page, cb);
},

buyFashionBuckz: function(msg) {
	var buttons = [ 
		{ text: 'Buy Fashion Bucks', handler: function(){ this.destroy();GAME.buyFashionBucks(); }, isdefault: false},
		{ text: "Close", handler: function(){ this.destroy(); }, isDefault:false } 
	];
	if (!GAME.player.hasValidated())
	{
		msg += '<br><br>If you haven\'t validated your email address yet, you can earn ' + GAME.player.getRegistrationBonus() + ' FBz by doing so. You can send yourself a validation email on the My Account page.';
		buttons.unshift({ text:"Go to My Account", handler: function(){ this.destroy();GAME.editAccount(); }, isDefault:false });
	}
	GAME.dialog({ 
				id:'nofbz-dialog',
				title: 'Oops',			
				body: msg,
				fixedcenter: true,   
				visible: true,  
				zIndex: 91,
				draggable: true, 
				constraintoviewport: true,
				width: '400px',
				modal: true,
				buttons: buttons,
				deleteOp:true
	});
	return false;	
},

changePassword: function(uid){
	var cb = function(d){
		var dialog = GAME.openForm({
			id: 'change-password-pop',
			title: 'Change Password',
			body: d,
			fixedcenter: true,
			visible: true,
			zIndex: 92,
			constraintoviewport: true,
			width: '400px',
			modal: true,
			buttons: [ 
				{ text: 'Reset', handler: function(){ GAME.resetPassword(); }, isdefault: true },
				{ text: 'Cancel', handler: function(){ this.destroy(); }, isdefault: false }
			]
		});
	};
	GAME.getPage("data/password.php?dui=" + uid, cb);
	return;
},

resetPassword: function(){
	var data = GAME.dialogs['change-password-pop'].getData();
	var post = '';	
	if(this.isPasswordValid(data)){
		for(var field in data){
			post += '&' + encodeURIComponent(field) + '=' + encodeURIComponent(data[field]);
		}
		var cb = {
			success: function(d){ 
				var response = eval('(' + d.responseText + ')');
				if(response['status'] == '1'){
					GAME.dialogs['change-password-pop'].destroy();
					GAME.alert(response['message']);
				}else{
					GAME.alert(response['message']);
				}
			}
		};	
		YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=change-password', cb, post);
	}
	return;
},

isPasswordValid: function(data){
	var oldpw = '';
	var newpw = '';
	var confpw = '';
	for(var field in data){
		if(field == 'oldpw'){ oldpw = data[field]; }
		if(field == 'newpw'){ newpw = data[field]; }
		if(field == 'confpw'){ confpw = data[field]; }
	}
	if(oldpw == '' || newpw == '' || confpw == ''){
		GAME.alert(GAME.ERROR_FILL_ALL_FIELDS);
		return false;
	}
	if(newpw != confpw){
		GAME.alert(GAME.ERROR_FILL_ALL_FIELDS_PASSWORD);
		return false;
	}
	return true;
},

IsNumeric: function(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
},

bookmark: function(type, ref_id, name) {
	if(type == undefined || ref_id == undefined) {
		return;
	}	
	var url = 'api.php';
	var post = 'action=bookmark'+'&type='+type+'&ref_id='+ref_id+'&name='+name;
	var cb = {
		success: function(d) {
			var code = parseInt(d.responseText);
			switch(code) {
				case -1:
					GAME.alert('Error');
				break;
				case 1:
					GAME.alert('Bookmarked');
				break;
				case 2:
					GAME.alert('Bookmark already exists');
				break;
				default:
				break;
			}
			GAME.bookmarkList();
		},
		failure: function(d) { 
		}
	};
	
	var result = YAHOO.util.Connect.asyncRequest('POST', url, cb, post);		
},

bookmarkList: function(){
	
	var url = "data/bookmarkList.php";
	var cb = function(d){
		var dialog = GAME.openForm({
			id: 'bookmark-list-dialog',
			body: d,
			//width: '200px',
			title: 'My Bookmarks',
			fixedcenter: false,
			constraintoviewport: true,
			xy: [827, 100],
			buttons: [
				{ text: 'Close', handler: function(){ this.destroy(); }, isDefault: false }
			],
			deleteOp:true
		});
	}
	GAME.getPage(url, cb);
},

removeBookmark: function(bookmark_id){
	if(bookmark_id == undefined) {
		return ;
	}
	var cb = {
		success: function(obj) { 
			GAME.bookmarkList();
			GAME.alert(GAME.constants.MESSAGE_BOOKMARK_REMOVED); 
		},
		failure: function(obj) { GAME.alert(GAME.constants.ERROR_TRY_AGAIN); }
	};
	function removeBookmark(){
		var url = "api.php?action=bookmark-remove&bookmark_id=" + bookmark_id;
		YAHOO.util.Connect.asyncRequest('GET', url, cb);
	}
	var m = GAME.dialog({ 
		id:'removeBookmark-dialog',
		title: 'Confrim',
		body: 'Do you really want to remove this bookmark?',
		fixedcenter: false,   
		visible: true,  
		modal: false,
		zIndex: 90,
		xy: [150, 280],
		draggable: true, 
		constraintoviewport: true,
		width: '350px',
		buttons: [ 
			{ text:"Remove It", handler: function() { removeBookmark(); this.destroy(); }, isDefault: false }, 
			{ text:"Close", handler: function() { this.destroy(); }, isDefault: true } 
		]
	});
},

setSite: function(site) {
	this.site = site;
},

getSite: function() {
	return this.site;
},

getRandomModel: function(size) {
// there is a PHP function which is identical to this
	return '/assets/models/model' + Math.floor(Math.random()*4+1) + (size != "" ? "_" + size : "") + '.png'
},

dhtmlLoadScript: function(url) {
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);
},

addThisWidget: function() {
	addthis_pub = 'FashionFantasyGame';
	this.dhtmlLoadScript("http://s7.addthis.com/js/152/addthis_widget.js");
},
startAdRePoz: function()
{
	this.adRePoz = true;
},
wideAdPoz: function()
{
    this.adRePoz = true;
    $("scraper_ad_frame").style.left = "-34px";
},
displayAd: function(type) { 
    try{
    switch(type) {
        case("leaderboard"):
            if (typeof(this.displayAd.leaderboard) == "undefined") {
                this.displayAd.leaderboard = document.getElementById("leaderboard_ad_frame");
            }
            this.displayAd.leaderboard.src = "/adframe.php?"
              + google_preview_param
              + google_debug_l_param
              + "type=leaderboard&"+this.constants.GAME_JS_RAND_NUM;;
            break;
        case("skyscraper"):
            if (typeof(this.displayAd.skyscraper) == "undefined") { 
                this.displayAd.skyscraper = document.getElementById("scraper_ad_frame");
            }
			this.displayAd.skyscraper.src = "/adframe.php?"
				+ google_preview_param
				+ google_debug_s_param
				+ "type=skyscraper&"+this.constants.GAME_JS_RAND_NUM;
			if(this.adRePoz)
			{
				this.adRePoz = false;
				$("scraper_ad_frame").style.left = "134px";
				$("scraper_ad_frame").style.top  = "155px";
			} else 
			{
				$("scraper_ad_frame").style.left = "-34px";
				$("scraper_ad_frame").style.top  = "150px";
			}
            break;
        case("mainboard"):
            if (typeof(this.displayAd.mainboard) == "undefined") {
                this.displayAd.mainboard = document.getElementById("mainboard_ad_frame");
            }    
			this.displayAd.mainboard.src = "/leaderboard.php?type=leaderboard_gameboard&"+this.constants.GAME_JS_RAND_NUM;
            break;
        case("mediumRectangle"):
            this.displayAd.mediumrectangle = getChildWithId(document.getElementById(paneSwitch.lastPane), "ad_frame");

            this.displayAd.mediumrectangle.src = "/adframe.php?"
							+ google_preview_param
							+ google_debug_m_param
            	+ "type=mediumrectangle&"+this.constants.GAME_JS_RAND_NUM;
            break;
	case("videoegg_doc"):
//		alert('Doc ad should display now');
		vedoc = document.getElementById('videoegg_doc_loader_frame');
		vedoc.src = '/ads/snippets/videoegg/doc_loader_frame.php?' + Math.random();
		break;
	case("defuse_videoegg_doc"):
		vedoc = document.getElementById('videoegg_doc_loader_frame');
		vedoc.src = 'blank.html';
		break;
	default: 
		break;
    }
    } 
    catch(e) {} 
},
liveHost: function() {
    var live = (window.location.host == "www.fashionfantasygame.com" || window.location.host == "fashionfantasygame.com" ? true : false);
    this.liveHost = function() {
        return live;
    }
    return this.liveHost()
},

trackPageView: function(path) {
    if (this.liveHost()) {
        pageTracker._trackPageview(path);
    }
    this.displayAd('leaderboard');
    this.displayAd('skyscraper');
},
/*findSanta: function(where) {
	if (!GAME.findSanta.found) {
		soundManager.play('hohoho');
		
		$('santa_img').style.display = 'none';
		YAHOO.initial_load.container.wait.show();
		var post = 'where=' + where;

		var cb = {
			success: function(d){
				YAHOO.initial_load.container.wait.hide();	
				GAME.alert("<b>You found me!</b><br /><br />HoHoHo - you'll find a gift of <b>"+GAME.findSanta.amount+"FBz</b> in your account.  Only one gift per player per day.<br /><br />Look for me again tomorrow!",'Woohoo!');
				GAME.findSanta.found = true;	
			},
			failure: function(d){
				YAHOO.initial_load.container.wait.hide();
				GAME.alert('Sorry, there was a problem.  Please try again.', 'Hmmm');
			}
		};
		YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=update-scav-hunt', cb, post);
	}
	else {
		GAME.alert('Hey, you already found me today!  Check back tomorrow!', 'Oops!');
	}
},

checkForSanta: function() {
	/* start hidden santa 
	if (!GAME.findSanta.found) {
		var attributes = { opacity: { from:0, to:1 } }; 
		var santa_animation = new YAHOO.util.Anim('santa_img', attributes, 1, YAHOO.util.Easing.easeIn); 
		
		if (isIE) {
		santa_animation.onComplete.subscribe(function() { 
				$('santa_img').filters[0].enabled=false
		});
		}

		santa_animation.animate();
	}
	/* end hidden santa 
},
*/
number_of_pageviews: 0,
process_history: function() {
    var _popped = false;
    var _peeked = false;    
    var data = false;
	if (arguments.length == 0) {
	// this implements "BACK"
		if (this.history.size() < 2) {
			// go home
			this.home();
			return;
		}
        
        try {
            _popped = this.history.pop();           
            _peeked = this.history.peek();
        }
        catch(e) {
            _popped = {id:false,where:true};
            _peeked = {id:true,where:false};
        }
        
        if (_peeked.where !== _popped.where || _peeked.id !== _popped.id) {
            try {
                data = this.history.pop();
            }
            catch(e) {
                data = false;
            }
        	this.gotoPage(data);
        }
	}
	else if (arguments.length == 1) {
        try {
            _peeked = this.history.peek();
        }
        catch(e) {
            _peeked = {id:0,where:false};
        }
        pagetype='reload';
        
        if (_peeked === undefined || _peeked.where != arguments[0].where || _peeked.id != arguments[0].id) {
   			this.history.push(arguments[0]);
   			pagetype='pageview';

   			if (++this.number_of_pageviews == 5)
   				GAME.displayAd('videoegg_doc');
   			if (this.number_of_pageviews == 6)
   				GAME.displayAd('defuse_videoegg_doc'); //unload the iframe, so a full reload won't trigger it again
   		}
		
		YAHOO.util.Connect.asyncRequest('POST',
		 'api.php?action=activity-log',
		 { success: function(d){}, failure: function(d){}}, 
		 'type='+pagetype+'&where='+arguments[0].where+
		 '&id='+arguments[0].id
		 );
	}
	else {
		this.home();
	}

	return;
},

// ---------------------------
//
// gotoPage({where,id}) -- jumps to an internal page
//
// used by history, and URL-based jumps to internal game pages
//
// ---------------------------

gotoPage: function () {
	var loc=arguments[0];
	if (loc === false) {
		this.home();
	}		
	else {
		switch(loc.where) {
			case('profile'):    this.viewProfile(loc.id); break;
			case('store'):      GAME.browseStore(loc.id); break;
			case('myshowroom'): GAME.myShowroom(); break;
			case('showroom'):   GAME.viewShowroom(loc.id);	break;
			case('closet'):		GAME.closet(loc.id); break;
			case('design'):     GAME.newDesign(); break;
			case('samples'):    GAME.myDesigns(); break;
			case("meetdesigners"):  GAME.meetDesigners(); break;
			case("sellDesigns"):GAME.sellDesigns(); break;
			case("goShopping"): GAME.goShopping(); break;
            case("twoDollarStore"): GAME.dollarStore(); break;
            case("twoDollarStore:cart"): GAME.dollarStore({page:'cart'}); break;
            case("twoDollarStore:wishlist"): GAME.dollarStore({page:'wishlist'}); break;
            case("twoDollarStore:featured"): GAME.dollarStore({page:'featured'}); break;
            case("twoDollarStore:bundles"): GAME.dollarStore({page:'bundles'}); break;
            case("twoDollarStore:category"): GAME.dollarStore({page:'category',id:loc.id}); break;
            case("twoDollarStore:item"): GAME.dollarStore({page:'item',id:loc.id}); break;
			case("rankings"):   GAME.rankings(); break;
			case("cafe"):
			case("loadCafe"):   GAME.loadCafe(); break;
			case("loadstores"): GAME.chooseAnotherStore(); break;
			case("ads"):        GAME.ads(); break;
			case("thebank"):    GAME.thebank(); break;
			case("mailBox"):    GAME.mailBox(); break;
			case("editLogo"):   GAME.editLogo(); break;
			case("fashionLog"): GAME.fashionLog(loc.id); break;
			case("personal_library"): GAME.loadPersonalLibrary(loc.id); break;
			case("contest"):      GAME.contestPage(); break;
			case("blahblahBlog"): GAME.blahblahBlog(); break;
			case("myffg"):			GAME.myFFG(); break;
			case("editAccount"):	GAME.editAccount(); break;
			case("runwayGame"):	GAME.runwayGame(); break;
			case("home"):
			default:			this.home(); break;
		}
	}
},

homepagePopup: function() {
	
	var body = $('popup_text').innerHTML;
	
	if (typeof(body) === "undefined" || body == "") {
		body = "Enjoy the Game!";
	}
	
	try {
		var dialog = GAME.dialog({
    		id: 'homepagePopup-dialog',
    		body: '<div style="text-align:left; padding:5px; border-bottom:1px solid #C0C0C0">' + body + '</div>',
    		width: '420px',
    		title: 'New Features',
    		constraintoviewport: true,
    		xy: [240, 173],
    		fixedcenter: false,
    		deleteOp: true
    	});
	}
	catch (e) {}
},
updateParentsEmail: function(email) {

	var cb = function(data){
		YAHOO.initial_load.container.wait.hide();
		var d = GAME.dialog({
			id: 'update-parents-email',
			width: '400px',
			title: 'Update Parents Email',
			body: data,
			modal: true,
			fixedcenter: true,
			buttons: [ 
				{text:'Submit', handler: function(){ this.submit(); }, isDefault: true },
				{text:'Cancel', handler: function(){ this.destroy(); }, isDefault: false }
			],
			deleteOp: true
		});
		d.callback = {
			success: function(d){
				var code = parseInt(d.responseText);
				switch(code) {
					case(1):
						GAME.alert('Thank you!  An email has been sent to your parents.', 'Success');
						break;
					case(2):
						GAME.alert('Sorry, the emails do not match!', 'Oops');
						break;
					case(3):
					default:					
						GAME.alert('There was an error.  Please try again.', 'Oops');
						break;
				}
			},
			failure: function(){}
		}
		d.validate = function(){
			var data = this.getData();
			if(data.p_email_1 == "" || data.p_email_2 == ""){
				GAME.alert("Please enter an email address!");
				return false;
			}
			if(data.p_email_1 != data.p_email_2) {
				GAME.alert("Please enter matching email addresses!");
				return false;
			}
			return true;
		};
	}
	this.getPage('data/updateParentEmail.php', cb);
},

displayTermsAndConditionsCheck: function() {
	var host = window.location.host;
    var dTerms = GAME.dialog({
        id: 'terms-dialog',
        body: '<div style="text-align:left; padding:5px; border-bottom:1px solid #C0C0C0"><form name="dlgForm" method="post"><b>FashionFantasyGame Player Update</b><br /><br />From time to time FashionFantasyGame.com updates our policies.  We have recently updated our <a style="color:blue;text-decoration:underline;" href="#" onclick="javascript:popup_w(\'http://' + host + '/footer_window.php?id=35\',\'ffg_info\')">terms of use</a>.<br /><br /><input type="checkbox" name="terms" id="terms" />&nbsp;&nbsp;I agree to the terms and conditions listed <a style="color:blue;text-decoration:underline;" href="#" onclick="javascript:popup_w(\'http://' + host + '/footer_window.php?id=35\',\'ffg_info\')">here</a>.</form></div>',
        width: '420px',
        title: 'Terms & Conditions',
        constraintoviewport: true,
        modal:  true,
        xy: [240, 173],
        fixedcenter: false,
        buttons: [
            { text: 'I accept!', handler: function(){ this.submit(); }, isDefault: false }
        ],
        deleteOp: true
    });
    
    dTerms.doSubmit = function() {
        var url = "/api.php?action=acceptterms";
        
        YAHOO.initial_load.container.wait.show();
        
        var result = YAHOO.util.Connect.asyncRequest('GET', url, dTerms.callback);
    }
    
    dTerms.callback = {
        success: function(d){
            YAHOO.initial_load.container.wait.hide();
            GAME.alert('Thank you!', 'Message');
        },
        failure: function(d) {
            YAHOO.initial_load.container.wait.hide();
            GAME.alert('Sorry, there was an error.  Not to worry, you can try again next time you log in.', 'Oops!');
        }
    }

    dTerms.validate = function() {
        var data = this.getData();
        if (data['terms'] === true) {
            return true;
        }
        
        GAME.alert('You forgot to check the checkbox!', 'Oops');
        return false;
    }
},

no_comma: function () {
	// if you put a comma after this function, IE will not forgive you
}

} // end object
