/*js GAME functions */
/**************************************************
*
* Global Functions
*
***************************************************/

function logRequest() {
    // reques to simulate page view for quantcast
    YAHOO.util.Connect.asyncRequest('GET', 'p.html', null);	
}

function $(id){
	return document.getElementById(id);
}

function escSQ(str)
{
	return str.replace(/'/, "\\'");
}
function escDQ(str)
{
	return str.replace(/"/, '\\"');
}

function markerLogo(marker_text, marker_logo, marker_link, marker_bonus, marker_token, positioning)
{
	var imgsrc = markerImgsrc(marker_logo);
	var onclick = markerOnclick(marker_link, marker_bonus, marker_token);

	
	if (typeof(positioning) == 'undefined')
		positioning = 'right:0; bottom:0;';
	return '<img title="' + escDQ(marker_text) + '" onclick="' + onclick + '" style="cursor:pointer; border:none; z-index:210; position:absolute; ' + positioning + '" src="' + imgsrc + '" />';
}
function markerOnclick(marker_link, marker_bonus, marker_token)
{
	return 'window.open(\'' + marker_link + '\',\'_blank\'); var e=arguments[0]; if (e && e.stopPropagation) e.stopPropagation(); else event.cancelBubble=true;' +
		(marker_bonus ? ' GAME.oneTimeBonus(' + GAME.player.uid + ',' + marker_bonus + ',\'Bonus for visiting a sponsor\\\'s item.\',\'' + marker_token + '\');' : '');
}
function markerImgsrc(marker_logo)
{
	return '/images/marker_logos/' + marker_logo;
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function paneSwitch(which){
    // right here, we set all the images to null.  
    //This prevents us from loading images when the panel is not in view.  
    //We only do this for panels that are not cached (meetdesigners)	
    if (paneSwitch.lastPane !== false) {
		if ((paneSwitch.lastPane === "V" ||
			 paneSwitch.lastPane === "N" ||
			 paneSwitch.lastPane === "B"))
		{
			var imgcnt = 0,
				imgs = jQuery('div#'+paneSwitch.lastPane+' img');
				
			// we use jQuery here bc its much faster than yui when it comes to selectors
			if (paneSwitch.cache[paneSwitch.lastPane] === undefined || paneSwitch.cache[paneSwitch.lastPane] !== imgs.length) {
				imgs.each(function() {
							if (this.complete !== undefined && this.complete !== true) {
								this.src = null;
							}
							else {
								imgcnt++;
							}
				});
				paneSwitch.cache[paneSwitch.lastPane] = imgcnt;
			}

			// check if last pane was profile and current pane is not, in this case, change the game height and width back!
			if ((paneSwitch.lastPane === "V" && which !== "V") ||
				(paneSwitch.lastPane === "B" && which !== "B") )
			{
				if (typeof(paneSwitch.cache['game-footer']) == "undefined") {
					paneSwitch.cache['game-footer'] = $('game-footer');
				}
				if (typeof(paneSwitch.cache[paneSwitch.lastPane+'-panel']) == "undefined") {
					paneSwitch.cache[paneSwitch.lastPane+'-panel'] = $(paneSwitch.lastPane);
				}
				paneSwitch.cache['game-footer'].style.top = GAME.constants.GAME_FOOTER_TOP + 'px';
				paneSwitch.cache[paneSwitch.lastPane+'-panel'].style.height = GAME.constants.GAME_VIEW_HEIGHT + 'px';
				paneSwitch.cache[paneSwitch.lastPane+'-panel'].style.marginLeft = '0px';
				var anim = new YAHOO.util.Anim('game-view', {
					height: {
						to: GAME.constants.GAME_VIEW_HEIGHT
					}
				}, 1, YAHOO.util.Easing.easeIn);
				anim.animate();
			}
		}

		fadeSwap(which);
		paneSwitch.lastPane = which;
    } 
    
    fadeSwap(which);
    paneSwitch.lastPane = which;
    paneSwitch.cache = {};
}
paneSwitch.lastPane = false;
paneSwitch.cache = false;

var panes_tr = false;
var activePanel_tr = false;
function fadeSwap(which){
	var xy = YAHOO.util.Dom.getXY($('wrapper'));
    
	if (panes_tr==false) {
		var el = $('gameboard').getElementsByTagName('div');

		panes_tr = [];
		for(var x=0; x<el.length; x++) {
			if(el[x].className == 'game-panel') {
				el[x].style.position = 'absolute';
				panes_tr[panes_tr.length] = el[x];
			}
		}
	}
    
	for (var n=0,len=panes_tr.length; n<len; n++) {
		if(panes_tr[n].id != activePanel_tr) {
			panes_tr[n].style.left = '-900px';
			panes_tr[n].style.top = '100px';
			panes_tr[n].style.display = 'none';
		}
	}
    
	if (activePanel_tr && activePanel_tr!=which) {
		var attributes = {
			points: { to: [10, 1000] },
			zIndex: { from: 20, to: 9 }
		};
		var anim = new YAHOO.util.Motion(activePanel_tr, attributes, .25, YAHOO.util.Easing.bounceOut);
		anim.animate();					
	}
    
    var p = $(which);
	p.style.position = 'absolute';
	p.style.display = 'block';
	
	var to = [xy[0]+140, xy[1]+150];
	var attributes = {
		points: { from: [-900, 100], to:  to },
		zIndex: { from: 9, to: 20 }
	};
    
	var anim = new YAHOO.util.Motion(which, attributes, .25, YAHOO.util.Easing.easeIn);
	anim.animate();					
	activePanel_tr = which;
}

function slideTransition(which){

	soundManager.play('page');
	
	var qx1 = 10;
	var qx2 = -800;
	var qx3 = -1611;
	var qx4 = -2411;

	var qy1 = 100;
	var qs = -451;
	var qy2 = -1002;	
	var qy3 = -1553;
	var qy4 = -2124;
	
	var time = false;
	
	switch(which){
		case("input"):	var endPoint = Array($('x_mov').value, $('y_mov').value);break;
		case("A"):		var endPoint = Array(qx1, qy1);break;
		case("B"):		var endPoint = Array(qx2, qy1);break;
		case("C"):		var endPoint = Array(qx3, qy1);break;
		case("D"):		var endPoint = Array(qx4, qy1);break;
		case("D1"):		var endPoint = Array(qx4, qy1);break;
		case("D2"):		var endPoint = Array(qx4, qy1);break;
		default:
		case("E"):		var endPoint = Array(qx1, qy2);break;
		case("F"):		var endPoint = Array(qx2, qy2);break;
		case("G"):		var endPoint = Array(qx3, qy2);break;
		case("H"):		var endPoint = Array(qx4, qy2);break;
		case("I"):		var endPoint = Array(qx1, qy3);break;
		case("J"):		var endPoint = Array(qx2, qy3);break;
		case("K"):		var endPoint = Array(qx3, qy3);break;
		case("L"):		var endPoint = Array(qx4, qy3);break;
		case("M"):		var endPoint = Array(qx1, qy4);break;
		case("N"):		var endPoint = Array(qx2, qy4);break;
		case("O"):		var endPoint = Array(qx3, qy4);break;
		case("P"):		var endPoint = Array(qx4, qy4);break;
		case("Q"):		var endPoint = Array(qx4, qy4);break;
		case("R"):		var endPoint = Array(qx4, qy4);break;
		case("S"):		var endPoint = Array(qx4, qy4);break;
		case("T"):		var endPoint = Array(qx4, qy4);break;
		case("U"):		var endPoint = Array(qx4, qy4);break;
		case("V"):		var endPoint = Array(qx4, qy4);break;
		case("W"):		var endPoint = Array(qx4, qy4);break;
		case("X"):		var endPoint = Array(qx4, qy4);break;
		case("Y"):		var endPoint = Array(qx4, qy4);break;
		case("Z"):		var endPoint = Array(qx4, qy4);break;
		case("S1"):		var endPoint = Array(qx1, qs);break;
		case("S2"):		var endPoint = Array(qx2, qs);break;
		case("S3"):		var endPoint = Array(qx3, qs);break;
		case("S4"):		var endPoint = Array(qx4, qs);break;
	}
		
	if (!time) {
        time = .5;	
    }
	var attributes = {
		points: { to: endPoint }
	};

	var anim = new YAHOO.util.Motion('gameboard', attributes, time, YAHOO.util.Easing.easeOut);
	anim.animate();					
}

function notice(msg){
	
	soundManager.play('page');
	
	var oArg = {};
	oArg.html = msg;
	var oDialog = YAHOO.My.UI.Dialog.alert(oArg);
}

function dia(msg){

	soundManager.play('select');
	
	var oArg = {};
	oArg.html = msg;
	oArg.resize = 1;
	oArg.width = 300;
	oArg.height = 300;
	oArg.buttonText = 0;
	oArg.translucent = 1;
	YAHOO.My.UI.Dialog.popup(oArg);
}

function popup(src, height, width){
	
	//soundManager.play('page');
	
	var oArg = {};
	oArg.html = '<iframe style="border: 0px;" height="' + height + '" width="' + width + '" src="' + src + '"></iframe>';
	oArg.resize = 1;
	oArg.width = width+20;
	oArg.height = height+20;
	oArg.buttonText = 'Done';
	oArg.translucent = 1;
	oArg.onBeforeClose = function(){
	
		GAME.openPanel.exit();
	}
	GAME.openPanel = YAHOO.My.UI.Dialog.modal(oArg);
}
function __panel(html, height, width){
	var oArg = {};
	oArg.html = html;
	oArg.resize = 0;
	oArg.width = width;
	oArg.height = height;
	oArg.buttonText = 'Close';
	oArg.translucent = 1;
	oArg.callback = function(){
	
		GAME.openPanel = false;
		//GAME.dialog.exit();
	}
	return YAHOO.My.UI.Dialog.popup(oArg);
}

function xxxpanel(src, height, width){
	
	var w = window.open(src, 'pop', 'toolbars=false,height=' + height + ',width=' + width);	
}

function panel(src, height, width){

	//soundManager.play('select');
	
	explain = false;
	var xmlPath = src;
	var reqs = new getXMXHTTPRequest();
	reqs.open("GET", xmlPath, true);
	//reqs.height = height;
	//reqs.width = width;
	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.openPanel = __panel(reqs.responseText, height, width);
				default:
			}
		} else {
			//alert('Problem: XMP HTTPRequest status: ' + req.status);
		}
	}
	reqs.send(null);
}

function dialog(msg, height, width){
	var oArg = {};
	oArg.html = msg;
	oArg.resize = 0;
	oArg.width = width;
	oArg._title = 'dialog';
	oArg.height = height;
	oArg.buttonText = 'Done';
	oArg.translucent = 1;
	YAHOO.My.UI.Dialog.popup(oArg);
}

function initPNG(img, src){
        img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='crop');";
        img.src = 'blank.gif';
        img.style.visibility = 'visible';
        img.className = '';
}

function hover_star(obj, index){
	
	var stars = obj.parentNode.getElementsByTagName('div');
	for(var n=0; n<stars.length; n++){
		if (n<index) {
            YAHOO.util.Dom.addClass(stars[n], 'hover');
        }
		else {
            YAHOO.util.Dom.removeClass(stars[n], 'hover');
        }
	}
}
function reset_stars(obj){
	var current_rating = obj.parentNode.getAttribute('title');
	
	var stars = obj.parentNode.getElementsByTagName('div');
	for(var n=0; n<stars.length; n++){
		//replace_class_star(stars[n]); // replace decimal star to normal complete star image..
		YAHOO.util.Dom.removeClass(stars[n], 'hover');
		if(n<current_rating){
			YAHOO.util.Dom.addClass(stars[n], 'on');
		} else {
			YAHOO.util.Dom.removeClass(stars[n], 'on');
			
		}
	}
}

function replace_class_star(obj){
	var classname = get_attribute(obj, "class");
    var names = [];
    var item = "";
    
	if(classname.indexOf("_") != -1){
        names = classname.split("_");
        if (names[0] != 'star') {
            item = names[0] + "_";
        }
		//obj.removeAttribute("class");
		//obj.setAttribute("class", "star");
		YAHOO.util.Dom.replaceClass(obj, classname, item+"star");
	}
}

function get_attribute(elem, value){
	if(elem.getAttribute(value)){
		return elem.getAttribute(value);
	}else{
		return elem.attributes[value].nodeValue;
	}
}

function set_rating(obj, rating){
		
	obj.setAttribute('title', rating);
	var stars = obj.getElementsByTagName('div');
	var rating_floor = (Math.floor(rating));
	var decimal_part = (rating % rating_floor);

	for(var n=0; n<stars.length; n++){
		YAHOO.util.Dom.removeClass(stars[n], 'hover');
		replace_class_star(stars[n]);
		if(n < rating){
			if(n == rating_floor){
				var decimal_star_class = get_decimal_star_class(decimal_part);
				YAHOO.util.Dom.replaceClass(stars[n], "star", decimal_star_class);
			}else{
				YAHOO.util.Dom.addClass(stars[n], 'on');
			}
		}else{
			YAHOO.util.Dom.removeClass(stars[n], 'on');
		}
	}
}

function get_decimal_star_class(decimal_part){

	if(0 < decimal_part && decimal_part <= 0.25){
		return "star_1_4 on";
	}else if(0.25 < decimal_part && decimal_part <= 0.5){
		return "star_1_2 on";
	}else if(0.5 < decimal_part && decimal_part <= 0.75){
		return "star_3_4 on";
	}
}

function submit_rating(type, id, rank){
if(type == undefined || !GAME.IsNumeric(id) || !GAME.IsNumeric(rank)) {
	return ;
}
	var url = "data/rating.php";
	var post = "type="+ type +"&id=" + id + "&rank=" + rank;
	var cb= {
		success: function(d){
			
			var data = GAME.evalResponse(d.responseText);
				
			var fb = $(type + '-ratingstatus-' + id);
			var ob = $(type + '-rating-' + id);
				
			//set_rating(ob, data.my_score);
			set_rating(ob, data.score);
			if ( type != "logo" && fb != null ){
				fb.innerHTML= data.text;
			}
			var cr = data.credit;
			if (cr>0)
				GAME.alert(cr+'FBz was added to your bank account'); 
		},
		failure: function(d){
			GAME.alert('rating error');
		}
	}
	var c = YAHOO.util.Connect.asyncRequest('POST', url, cb, post);	
}

/************
 * Need a fix for myshowroom to have tabs and access the caro object outside of when its defined
 * Using global variables till we can find a better way 
 *******************/
GAME.MYSHOWROOM_CLOTHES = new Array(4);
GAME.MYSHOWROOM_CLOTHES[0] = false;
GAME.MYSHOWROOM_CLOTHES[1] = false;
GAME.MYSHOWROOM_CLOTHES[2] = false;
GAME.MYSHOWROOM_CLOTHES[3] = false;

var MYSHOWROOM_WHERE = false;    
var MYSHOWROOM_lastClicked = '';
// show items that are available in at least one store
var MYSHOWROOM_showAvailableItems = false;
var MYSHOWROOM_tab = '';


GAME.patternHelp = function() {
	var p = window.open('assets/help/pattern_help.html','pat_help','resizable=yes,width=750,height;600,scrollbars=yes');
}
GAME.redeemCode = function(){
	//GAME.allowNav();
    GAME.trackPageView("/data/bank/redeemCode.php");
	var w = window.open('/data/bank/redeemCode.php','bucks2','resizable=yes,width=550,height=651,scrollbars=yes');
}

GAME.buyFashionBucks = function(){
    GAME.trackPageView("/data/bank/purchase_buckz.php");
	var host = window.location.host;
	var w = window.open('https://' + host + '/data/bank/purchase_buckz.php','bucks1','resizable=yes,width=450,height=561,scrollbars=yes');
}

GAME.buyGiftCodes = function(){
    GAME.trackPageView("/data/bank/purchase_giftcodes.php");
	var host = window.location.host;
	var w = window.open('https://' + host + '/data/bank/purchase_giftcodes.php','gift_codes','resizable=yes,width=600,height=600,scrollbars=yes');
}

GAME.blahblahBlogPreview = function(id) {
	GAME._blahblahBlog("/blahblahblog/main.php?id=" + id);
}
GAME.blahblahBlog = function() {
	GAME._blahblahBlog("/blahblahblog/main.php?id=live");
}
GAME._blahblahBlog = function(url) {
	var path = url;
	var panelID = "BLAHBLAHBLOG";
	GAME.adRePoz = true;
	GAME.trackPageView(path);
	GAME.process_history({'id':0,'where':'blahblahBlog'});
	GAME.loadPanel(path, panelID, function() 
	{
        ;
    });	
}
GAME.runwayGame = function() {
	/* PREVIEW LIMIT
	var c, vul, found = false, valid_users = [
		'i love nick13',
		'*',
		'~Zinnia~',
		'hello_kittynena1',
		'libbeth_designs',
		'pinkpearls',
		'desing set go',
		'Annabelle619',
		'Charmizzle',
		'catfrances',
		'chanel xo',
		'saphirebaby',
		'Glamor<3',
		'Lynnielois',
		'blakbury',

		'PinkyVi',
		'Bobby_NYC',
		'LuckyGanz',
		'test-designer-LA',
		'nyekk',
		'gegedesign',

		'*CUTEBARBIEDESIGNS*',
		'1icecrea12',
		'BananaBread',
		'Bunnnnyy97',
		'CuppyCake1998',
		'designerchick12',
		'Edem',
		'Fashiongurl989',
		'flower2442',
		'glittergirl24',
		'Haileygirl4',
		'lovelyangel9907',
		'music=my_life',
		'pinkpearls',
		'Red Rose Cutie',
		'Rosebud designs',
		'SpAzz1321',
		'tnt688',
		'Treasurerocks',
		'twirp08',
		'zeert'
	];
	vul = valid_users.length;
	for (c = 0; c < vul; c++)
	{
		if (GAME.player.uname == valid_users[c])
		{
			found = true;
			break;
		}
	}
	if (!found)
	{
		return; //user is not allowed to see the runway game
	}
	
	END PREVIEW LIMIT */

	var path = "/runwaygame/index.php";
	var panelID = "RUNWAYGAME";
	GAME.trackPageView(path);
	GAME.process_history({'id':0,'where':'runwayGame'});
	GAME.loadPanel(path, panelID, function() 
	{
        ;
    });	
}

// callback from the flash game 
GAME.rgPageView = function(page) {
	GAME.adRePoz = true;
	if (page.substr(0,6)=='splash')
	{
		GAME.trackPageView('/runwaygame/index.php?page='+page);
	}	
//	GAME.process_history({'id':page,'where':'runwayGame'});
	}
	
GAME.myFFG = function() {
	var path = "/community/myffg.php";
	var panelID = "MYFFG";
	GAME.adRePoz = true;
	GAME.trackPageView(path);
	GAME.process_history({'id':0,'where':'myffg'});
	GAME.loadPanel(path, panelID, function() 
	{
        ;
    });	
}

GAME.contestPage = function(type) {
//	GAME.trackPageView("/community/viewContests.php"); -- GAME.showContests(type) below calls these
//	GAME.process_history({'id':0,'where':'contest'});

	GAME.loadPanel('community/viewContests.php', 'R', function() 
	{
        if (GAME.contestManager == undefined) {
            GAME.contestManager = new ContestManager();
        }
        GAME.showContests((type === undefined)? 'default' : type)
    });	
	$("scraper_ad_frame").style.left = "-31px";
}


// head-to-head voting; voted s1 over s2
GAME.chooseHead2Head = function( cid, s1, s2, type) {
	var post = "contest_id=" + cid + "&first=" + s1 + "&second=" + s2
									+ "&third=" + 0 + "&voter_id=" + GAME.player.uid + "&type=diva";
			
	YAHOO.initial_load.container.wait.show();
		
	var cb = {
		success: function(d){
		YAHOO.initial_load.container.wait.hide();					
			var json = eval('(' + d.responseText + ')');
			var vote_success = json['vote_success'];
			var balance = json['balance'];
			var is_FBz_deposited = json['is_FBz_deposited'];
			var bonus = json['bonus'];
			var togo = json['togo'];
			var togoBonus = json['togoBonus'];
			//if (parseInt(d.responseText) == 1) {
			if(vote_success == "1"){						
				var msg = '<div>Thank you! Your vote has been recorded! </div>';
				if (togo>0) msg += '<div>' + togo + ' more votes to go to earn ' + togoBonus + ' FBz Bonus! </div>'; 
				else if (togo==0) msg += '<div>'+togoBonus+' FBz bonus deposited!</div>';
				GAME.alert(msg, "Success");
//				GAME.home();
			}
			else {
				GAME.alert("Sorry, there was an error.  Please try again!");
			}
		GAME.chooseContestWinner(cid,type);	
		},
		failure: function(d){}
	};
	YAHOO.util.Connect.asyncRequest('POST', 'api.php?action=contest-record-vote&', cb, post);
//	GAME.chooseContestWinner(cid,type);	
}

GAME.chooseContestWinner = function(id, type) {
	var c_url = false;

    if (type <= 3 || type == 200) { // designer and closet contests
        c_url = 'community/chooseContestWinner.php?id=' + id;
        GAME.trackPageView("/community/chooseContestWinner.php");
    }
    else if (type ==100) // for now Diva contests use head-to-head voting
    {
		GAME.adRePoz = true;
        GAME.trackPageView("/community/chooseContestWinner_diva.php");
        c_url = 'community/chooseContestWinner_diva.php?id=' + id;
    }
    else {
        GAME.trackPageView("/community/chooseContestWinner_store.php");
        c_url = 'community/chooseContestWinner_store.php?id=' + id;
    }

	GAME.loadPanel(c_url, 'S', function() {
	
//	if (typeof(GAME.contestManager) == "undefined") 
		GAME.contestManager = new ContestManager();
	(function() {
        var dd, dd2, dd3, dd4, clickRadius = 46, 
		startPos,startPos1,startPos2,startPos3,startPos4,startPos5,startPos6,startPos7,startPos8,startPos9,
        Event=YAHOO.util.Event, Dom=YAHOO.util.Dom, ToolTip=YAHOO.widget.Tooltip, DropDrag=YAHOO.util.DD;

        YAHOO.util.Event.onDOMReady(function() {
			/* create the "matrix" with 20 entries */
			for (var i = 0; i < 20; i++) {
				var el = Dom.get("clothing-item-" + i);
				tt0 = new ToolTip("tt" + i, { context: "clothing-item-" + i }); 
	            dd = new DropDrag(el);

				// our custom click validator let's us prevent clicks outside
				// of the circle (but within the element) from initiating a
				// drag.
				dd.clickValidator = function(e) {
	
					// get the screen rectangle for the element
					var el = this.getEl();
					var region = Dom.getRegion(el);
	
					// get the radius of the largest circle that can fit inside
					// var w = region.right - region.left;
					// var h = region.bottom - region.top;
					// var r = Math.round(Math.min(h, w) / 2);
					//-or- just use a well-known radius
					var r = clickRadius;
	
					// get the location of the click
					var x1 = Event.getPageX(e), y1 = Event.getPageY(e);
	
					// get the center of the circle
					var x2 = Math.round((region.right+region.left)/2);
					var y2 = Math.round((region.top+region.bottom)/2);
	
	
					// I don't want text selection even if the click does not
					// initiate a drag
					Event.preventDefault(e);
	
					// check to see if the click is in the circle
					return ( ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) <= r*r );
				};
	
				dd.onDragDrop = function(e, id) {
					_id = contest_item_ids[this.getEl().id.match(/(\d+)/g).toString()];
					GAME.contestManager.removePosition(_id);
					if (GAME.contestManager.setPosition(id,_id)) {
						// center it in the square
						Dom.setXY(this.getEl(), Dom.getXY(id));
					} else {
						this.onInvalidDrop(e);
					}
				}
	
				dd.onInvalidDrop = function(e) {
					// return to the start position
					//Dom.setXY(this.getEl(), startPos);
					// Animating the move is more intesting				
					var mymatch = /[0-9]+$/.exec(this.id);
					var i = mymatch[0];
					new YAHOO.util.Motion( 
						this.id, { 
							points: { 
								to: Dom.getXY("holder" + i)
							}
						}, 
						0.5, 
						YAHOO.util.Easing.easeOut 
					).animate();
	
					_id = contest_item_ids[this.getEl().id.match(/(\d+)/g).toString()];
	
					GAME.contestManager.removePosition(_id);
				}
				
				dd.isTarget = false;
			}
       

			dd2 = new YAHOO.util.DDTarget("first-place");
            dd3 = new YAHOO.util.DDTarget("second-place");
            dd4 = new YAHOO.util.DDTarget("third-place");
	   
	   });
    })();


});	
	// if configured, view it
	// else edit it
},

GAME.moreRankings = function() {

	var cb = function(d){
		var m = GAME.dialog({ 
			id:'ratings-categories-dialog',
			title: 'Rankings Categories',			
			body: d,
			fixedcenter: false,   
			visible: true,  
			zIndex: 90,
			xy: [80, 120],
			draggable: true, 
			constraintoviewport: true,
			width: '400px',
			modal: true,
			close: false,
			buttons: [ 
				{ text:"Cancel", handler: function(){ this.destroy(); }, isDefault:false } 
			]
		});
		
		m.callback = {
			success: function(d){
				
			},
			failure: function(d){

			}
		}
	}
	GAME.getPage("data/ratings/showRatingsCategories.php", cb);
}

GAME.seeAllRankings = function(id) {
	var div = document.getElementById('full_rankings');
	var f = GAME.dialogs['ratings-categories-dialog'];
	f.buttons = [ { text:"Back", handler: function(){ GAME.moreRankings(); }, isDefault:false }];

	div.innerHTML = "<img src='http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif' />";

	var cb = function(d){
		div.innerHTML = d;
	}
	GAME.getPage('data/ratings/listRankedUsers.php?id=' +id, cb);	
}

GAME.seeContestWinners = function(id) {
	var div = document.getElementById('all_winners');
	var f = GAME.dialogs['all-contests-dialog'];
	f.buttons = [ { text:"Back", handler: function(){ GAME.moreRankings(); }, isDefault:false }];

	div.innerHTML = "<img src='http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif' />";

	var cb = function(d){
		div.innerHTML = d;
	}
	GAME.getPage('data/contests/showContestWinners.php?id=' +id, cb);	
}

GAME.contestWinners = function(free) {
    if (free != 1) free = 0;

	var cb = function(d){
		var m = GAME.dialog({ 
			id:'all-contests-dialog',
			title: 'View All Contests',			
			body: d,
			fixedcenter: true,   
			visible: true,  
			zIndex: 90,
			xy: [80, 120],
			draggable: true, 
			constraintoviewport: true,
			width: '500px',
			modal: true,
			close: false,
			buttons: [ 
				{ text:"Cancel", handler: function(){ this.destroy(); }, isDefault:false } 
			],
			deleteOp: true
		});
		
		m.callback = {
			success: function(d){
			},
			failure: function(d){
			}
		}
	}
	GAME.getPage("data/contests/listAllContests.php?free="+free, cb);
}

GAME.backToMoreContests = function() {
	var div = document.getElementById('all_winners');
	
	div.innerHTML = "<img src='http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif' />";
	
	var cb = function(d){
		div.innerHTML = d;
	}

	GAME.getPage("data/contests/backToContests.php", cb);
}

GAME.backToMoreRankings = function() {
	var div = document.getElementById('full_rankings');
	
	div.innerHTML = "<img src='http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif' />";
	
	var cb = function(d){
		div.innerHTML = d;
	}

	GAME.getPage("data/ratings/showRatingsCategories.php", cb);
}

GAME.openPopup = function(user, id, text) {
	var o,tmp,c_user, c_text;

	if ( o == undefined )
		o = window.open('','contest_win','width=610,height=600,scrollbars=no,resizable=yes');

	tmp = o.document;
	tmp.write("<html><head><title>Contest Store View</title>");
	tmp.write("</head><body><b>Designed By:</b>" + unescape(user) + "<br /><img src=\"" + GAME.getAssetPath('rendered', id) + "\"><p><b>Why my store rocks:</b><br />" + unescape(text) + "</p>");
	tmp.write("<p><a href=\"javascript:self.close()\">Close</a> the popup.</p>");
	tmp.write("</body></html>");
	tmp.close();
}


GAME.lotsList = function(page){

	var neighborhood = 1;
	var id = 'lots-list';
	var obj = this;
	var fun = obj.lotsList;
	
	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;
			return;
		} 
		GAME.dialog({
			id: id,
			body: d,
			title: 'Lots - page #' + (obj.page+1),
			width: '800px',
			buttons: [
			  { text: 'Previous', handler: function(){ fun(obj.page-1); }, isdefault: true },
			  { text: 'Next', handler: function(){ fun(obj.page+1); }, isdefault: true },
			  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
			],
			deleteOp: true	
		});
	}
	GAME.getPage('data/lots.php?start=' +obj.page, cb);
}

GAME.viewShowroom = function(id, first_design){
	var rand_str = GAME.constants.GAME_JS_RAND_NUM;
	var model = false;
	GAME.MYSHOWROOM_CLOTHES.length = 0; // clear the array
	GAME.MYSHOWROOM_CLOTHES[0] = false;
	GAME.MYSHOWROOM_CLOTHES[1] = false;
	GAME.MYSHOWROOM_CLOTHES[2] = false;
	GAME.MYSHOWROOM_CLOTHES[3] = false;	
	GAME.showroomTab.cached.length = 0;		// clear out the cache
	GAME.showroomTab.whereami = 'othershowroom';
	
	if(!GAME.IsNumeric(id)) {
		return ;
	}
	
	// track history
	GAME.process_history({'id':id,'where':'showroom'});
	
	MYSHOWROOM_showAvailableItems = false;
	MYSHOWROOM_tab = '';
  
	if(typeof(first_design)!="undefined" && first_design != null) {
		first_design_arg = "&first_design=" + first_design;
		first_design_cb = function(){GAME.new_showroomViewItem(first_design);};
	}
	else {
		first_design_arg = "";
		first_design_cb = function(){};
	}
	
	setTimeout("soundManager.play('cameras')", 800);
	
	MYSHOWROOM_lastClicked = '';
	this.designerDisplayed = id;
		
    GAME.trackPageView("/community/designerShowroom2.php");
	
	GAME.loadPanel('community/designerShowroom2.php?id=' + id + first_design_arg, 'O', function(){
			model = GAME.getRandomModel('showroom');
			
			var config = {
				numVisible: 5,
				scrollInc: 5,
				btnLeftEnabled: '/images/showroom_new/yellow_btn_left.png',
				btnLeftDisabled: '/images/showroom_new/yellow_btn_left.png',
				btnRightEnabled: '/images/showroom_new/yellow_btn_right.png',
				btnRightDisabled: '/images/showroom_new/yellow_btn_right.png',
				paginationDivId:  'clothespager',
				formatItem: function(data){
				    design_class = (data.size_style == 'NEW_SIZE') ? 'design' : 'design_old';
				    
					str = '<div id="model" align="center" style="position:relative; border: 0px solid black; margin: 0px; float: left;  width: 105px;">';

					str+= '<div onclick="GAME.new_showroomViewItem('
									+ data.id 
									+ ');" style="cursor: pointer; border: 0px solid black; overflow: hidden; height: 280px; width: 105px; margin-top: 0px;">'
									+ ( (parseInt(data.qty)<=0 && (GAME.player.type == 2 || GAME.player.id == id)) ? '<img src="images/soldout.png" style="border:none; padding-top:20px; position:absolute;" width=70 />': '')
									+ ( data.marker_logo ? markerLogo(data.marker_text, data.marker_logo, data.marker_link, data.marker_bonus, data.marker_token): '')
									+ '<img src="/images/divas/skinM_eyesBl_hairBla_closet.png'
									+ '" class="' + design_class + '" style="position:absolute;top:0;left:0">'
									+ '<img src="' + GAME.getAssetPath('produced', data.id, null, GAME.constants.GAME_JS_RAND_NUM) 
									+ '" class="' + design_class + '" style="position:absolute;top:0;left:0"></div>';
									
//					if ( (parseInt(data.qty)<=0) && (GAME.player.type == 2 || GAME.player.id == id)) {
//						str	+='<div onclick="GAME.new_showroomViewItem('
//							+ data.id 
//							+ ');" style="cursor: pointer; border: 0px solid black; overflow: hidden; height: 280px; width: 105px; margin-top: 0px; background-image: url(/images/showroom_new/model.png);"><img src="images/soldout.png" style="border:none; padding-top:20px; position:absolute;" width=70 /><img src="'
//							+ GAME.getAssetPath('produced', data.id, null, rand_str) 
//							+ '" class="'
//							+ design_class
//							+ '"></div>';
//					}
//					else {
//						str	+='<div onclick="GAME.new_showroomViewItem('
//							+ data.id 
//							+ ');" style="cursor: pointer;border: 0px solid black; overflow: hidden; height: 280px; width: 105px; margin-top: 0px; background-image: url(/images/showroom_new/model.png);"><img src="'
//							+ GAME.getAssetPath('produced', data.id, null, rand_str) 
//							+ '" class="'
//							+ design_class
//							+ '"></div>';
//					}
					str += '<div name="ShowRoomSelector" class="selector" id="selector_'
						+ data.id 
						+ (MYSHOWROOM_showAvailableItems === true ? '_instores' : '') 
						+ '" style="display:none;"></div></div>';
					
					return str;
				},
				dataSource: 'designerAPI.php?action=getDesigns&owner=' + id + first_design_arg,
				wrap: true,
				initialLoadCallback: first_design_cb
			}
			
			//figure out what type of clothing to show first
			first_clothing_type = $('showroom_first_type').value;

			GAME.viewShowroom.caro_config = config;
			GAME.MYSHOWROOM_CLOTHES[first_clothing_type] = new Caro('showroom-clothes-'+first_clothing_type, first_clothing_type, config, true);
			$('showroom-clothes-'+first_clothing_type+'-btns').style.display='block';
			GAME.showroomTab.cached[first_clothing_type] = true;			
			GAME.MYSHOWROOM_CLOTHES[first_clothing_type].clothesLoaded.subscribe(
						(function(btn_ref, div_ref, cached_type, load_ref) {
							return function(type, args) { 
									if (args[0].total == 0) {
									GAME.showroomTab.cached[cached_type] = 0;
									btn_ref.style.display='none';
									div_ref.innerHTML = 'No ' 
														+ (args[0].type==1 
															? "Tops" 
															: (args[0].type==2 
																? "Outfits" 
																: (args[0].type==3 
																	? "Dresses" 
																	: ""))) 
														+ ' Found!';
									div_ref.style.display = 'block';
									}
									load_ref.style.display = 'none';									
								}
						})($('showroom-clothes-'+first_clothing_type+'-btns'),$('not_found'),first_clothing_type,$('showroom_loading_image'))); 
			
			$('showroom-clothes-'+first_clothing_type).style.display = 'block';
			$('showroom-clothes-'+first_clothing_type+'-btns').style.display='block';
			
			if(GAME.player.type != 2){ //if they are not a store owner we need to set up the where to buy carousel
						
		  	//set up the carousel for the where 2 buy box
			  var config = {
			    numVisible: 4,
			  	btnLeftEnabled: '/images/showroom_new/yellow_btn_left.png',
				  btnLeftDisabled: '/images/showroom_new/yellow_btn_left.png',
				  btnRightEnabled: '/images/showroom_new/yellow_btn_right.png',
				  btnRightDisabled: '/images/showroom_new/yellow_btn_right.png',
				  formatItem: function(data){
				      //remove slashes from logo html
					logoHTML = data.logoHTML;
					logoHTML=logoHTML.replace(/\\'/g,'\'');
					logoHTML=logoHTML.replace(/\\"/g,'"');
					logoHTML=logoHTML.replace(/\\\\/g,'\\');
					logoHTML=logoHTML.replace(/\\0/g,'\0');
					//str = '<div class="store" onclick="GAME.browseStore(\''+data.id+'\', \''+ data.location+'\', \'' + data.design_id + '\');"><div class="logo">'+ logoHTML +'</div><div class="name">' + data.name + '</div></div>';
					str = '<div class="store" onclick="GAME.browseStore('
						+ data.id
						+ ', '
						+ data.location
						+ ', '
						+ data.design_id 
						+ ', '
						+ data.city 
						+ ');"><div class="logo">'
						+ logoHTML 
						+ '</div><div class="name">' 
						+ data.name 
						+ '</div></div>';

					return str;
				   },
				  dataSource: 'designerAPI.php?action=getDesignByLocation',
				  wrap: true
				  
			  }
			  MYSHOWROOM_WHERE = new Caro('showroom-where', first_clothing_type, config, true);
			}
			
			$('showroom_back').onclick = function(){GAME.process_history()};
	});
}
GAME.viewShowroom.caro_config = false;

GAME.showroomTab = function(tab){
	$('showroom_loading_image').style.display = "block";
	$('not_found').style.display = "none";
	$('no_stores').innerHTML = "";
	var tab_text = '';
	
	GAME.new_showroomViewItem.lastRing.hide();
  
	//first make sure all the tabs are set to the right state
	var tab_tops = (tab == 'tops') ? '_a' : '';
	var tab_dresses = (tab == 'dresses') ? '_a' : '';
	var tab_outfits = (tab == 'outfits') ? '_a' : '';

	$('showroom_tab_tops').src = '/images/showroom_new/tops' + tab_tops + '.png';
	$('showroom_tab_dresses').src = '/images/showroom_new/dresses' + tab_dresses + '.png';
	$('showroom_tab_outfits').src = '/images/showroom_new/outfits' + tab_outfits + '.png';

	var gtype = 1;
	if(tab == 'tops'){
		gtype = 1;
		tab_text = 'Tops';
	}
	else if(tab == 'dresses'){
		gtype = 3;
		tab_text = 'Dresses';		
	}
	else if(tab == 'outfits'){
		gtype = 2;
		tab_text = 'Outfits';		
	}

	MYSHOWROOM_tab = tab;
  
	//refresh the carousel
	/*MYSHOWROOM_CLOTHES.garmentType = gtype;
	MYSHOWROOM_CLOTHES.total= undefined;
	MYSHOWROOM_CLOTHES.car.clear();
	MYSHOWROOM_CLOTHES.car.reload(4);*/

	$('showroom-clothes-1').style.display='none';	
	$('showroom-clothes-1-btns').style.display='none';
	$('showroom-clothes-4').style.display='none';	
	$('showroom-clothes-4-btns').style.display='none';	
	$('showroom-clothes-2').style.display='none';	
	$('showroom-clothes-2-btns').style.display='none';	
	$('showroom-clothes-5').style.display='none';	
	$('showroom-clothes-5-btns').style.display='none';	
	$('showroom-clothes-3').style.display='none';	
	$('showroom-clothes-3-btns').style.display='none';	
	$('showroom-clothes-6').style.display='none';	
	$('showroom-clothes-6-btns').style.display='none';	
	
	var instores_types = (MYSHOWROOM_showAvailableItems === true ? gtype+3 : 0);
	var type_to_check = (instores_types > 0 ? instores_types : gtype);
	
	if (GAME.showroomTab.cached[type_to_check] === undefined) {
		GAME.MYSHOWROOM_CLOTHES[type_to_check] = new Caro('showroom-clothes-'+type_to_check, 
												  gtype, 
												  (GAME.showroomTab.whereami == 'myshowroom' 
													? GAME.myShowroom.caro_config 
													: GAME.viewShowroom.caro_config),
												  true);
		GAME.showroomTab.cached[type_to_check] = true;
		GAME.MYSHOWROOM_CLOTHES[type_to_check].clothesLoaded.subscribe(
					(function(btn_ref, div_ref, cached_type, load_ref) {
						return function(type, args) {
								if (args[0].total==0) {
								GAME.showroomTab.cached[cached_type] = 0;
								btn_ref.style.display = 'none';
								div_ref.innerHTML = 'No ' 
													+ (args[0].type==1 
														? "Tops" 
														: (args[0].type==2 
															? "Outfits" 
															: (args[0].type==3 
																? "Dresses" 
																: "")))
													+ ' Found!</div>';
								div_ref.style.display = 'block';
								}
								load_ref.style.display = 'none';
							}
					})($('showroom-clothes-'+gtype+'-btns'),$('not_found'),type_to_check,$('showroom_loading_image')));
	}
	else {
		$('showroom_loading_image').style.display = 'none';									
	}
	
	if (MYSHOWROOM_showAvailableItems === true) {
		$('showroom-clothes-'+gtype).style.display = 'none';
		$('showroom-clothes-'+gtype+'-btns').style.display='none';		
		$('showroom-clothes-'+instores_types).style.display = 'block';
		$('showroom-clothes-'+instores_types+'-btns').style.display='block';
	}
	else {
		$('showroom-clothes-'+(gtype+3)).style.display = 'none';	
		$('showroom-clothes-'+(gtype+3)+'-btns').style.display='none';	
		$('showroom-clothes-'+gtype).style.display = 'block';
		$('showroom-clothes-'+gtype+'-btns').style.display='block';
	}

	if (GAME.showroomTab.cached[type_to_check] == 0) {
		$('not_found').style.display = "block";
		$('not_found').innerHTML = "No " + tab_text + " Found!";
	}
	else {
		$('not_found').style.display = "none";
		$('not_found').innerHTML = "";		
	}
	
	//clear the item details selection
	$('showroom_item_details').innerHTML = '';

	GAME.MYSHOWROOM_CLOTHES[type_to_check].updatePagination(GAME.MYSHOWROOM_CLOTHES[type_to_check].totalPages,GAME.MYSHOWROOM_CLOTHES[type_to_check].car.currpage) // refresh pagination for selected tab

	if(GAME.player.type == 2){
		$('buy_4_store').innerHTML = '';    
	}
	else {
	//clear the where 2 buy section
	/*alert(MYSHOWROOM_WHERE.car.getProperty('size'));
	for (a in MYSHOWROOM_WHERE) {
		if (confirm(a)) if(!confirm(MYSHOWROOM_WHERE[a])) break;;
	}*/
		if (MYSHOWROOM_WHERE.total) 
			MYSHOWROOM_WHERE.car.clear();
	}
	
	//clear the selected design in the your style box on "my showroom page"
	yourstyle = $('mystyle_design');
	if(yourstyle != null)
	yourstyle.src = "/assets/blank.gif";
}
GAME.showroomTab.cached = [];
GAME.showroomTab.availableInStores = [];
GAME.showroomTab.availableInStore_cache = [];
GAME.showroomTab.needsUpdating = false;
GAME.showroomTab.whereami = false;

GAME.showroomAvailableItems = function() {
	GAME.new_showroomViewItem.lastRing.hide();
	if(MYSHOWROOM_showAvailableItems == false) {
		MYSHOWROOM_showAvailableItems = true;
	}
	else {
		MYSHOWROOM_showAvailableItems = false;
	}
	$('available_items_checkbox').checked = MYSHOWROOM_showAvailableItems;	
	
	GAME.showroomShowItems();
}

GAME.showroomShowItems = function() {
	GAME.showroomTab(MYSHOWROOM_tab);	
}

GAME.usersList = function(page){
	
	var obj = this;
	
	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;
			return;
		} 
		var dialog = GAME.dialog({
					id: 'users-list',
					body: d,
					title: 'Users - page #' + (obj.page+1),
					width: '800px',
					close: false,
					buttons: [
					  { text: 'Previous', handler: function(){ obj.usersList(obj.page-1); }, isdefault: true },
					  { text: 'Next', handler: function(){ obj.usersList(obj.page+1); }, isdefault: true },
					  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
					],
					deleteOp: true
				});
	}
	GAME.getPage('data/users.php?start=' +obj.page, cb);
}

GAME.meetDesigners = function(){

	var cb = function(d){
		GAME.loadDesigners(0);
		//GAME.alert('laoded the designers interface');
	}
	
    GAME.trackPageView("/community/designers.php");
	
   	GAME.process_history({'id':0,'where':'meetdesigners'});

    GAME.loadPanel('community/designers.php', 'N', cb);
	return;
	
	if(this.designerBrowser){
		this.designerBrowser.viewListing();
		
	} else {
		this.designerBrowser = new MeetDesigners();
	}
}

/*****************************************
*
* Ratings
*
******************************************/
GAME.rankings = function(){
	
    GAME.trackPageView("/data/ratings/stats.php");
	
    GAME.process_history({'id':0,'where':'rankings'});
    
	if (GAME.rankings.cache === true) {
		paneSwitch('L');
	}
	else {
		GAME.loadPanel('data/ratings/stats.php', 'L');	
		GAME.rankings.cache = true;
	}

}
GAME.rankings.cache = false;

/******************
*
* Preferences
* 
*******************/
GAME.preferences = function(){
	
	var url = 'data/help/preferences.php';
	var cb = function(d){
		
		var dialog = GAME.dialog({
			id: 'preferences',
			body: d,
			width: '400px',
			title: 'Your Preferences',
			modal: true,
			fixedcenter: true,
			buttons: [ 
				{text: 'Save', handler: function(){ dialog.submit(); }, isDefault: true },
				{text: 'Cancel', handler: function(){ dialog.cancel(); }, isDefault: false }
			]
		});
		
		// add some subscribers
		dialog.beforeSubmitEvent.subscribe(function(d, dd){ 
			
		
		}, dialog);
		
		dialog.submitEvent.subscribe(function(d, dd){ 
			
			//GAME.assistantEnabled = dialog.getData().feedback;
			GAME.autoCheckMessages = dialog.getData().msgcheck;
					
		}, dialog);
	}
	GAME.getPage(url, cb);
} // end preferences

/************************************************
*
* Reporting a user
*
*************************************************/
GAME.reportUser = function(user_id, type, reference){
	if(type == undefined)
    type = '';
	if(reference == undefined)
    reference = '';
  if(user_id == undefined)
    return;
    
   var cb = function(d){
    //for some reason trybuy is getting fired automatically.. not sure why
     var report = function(){
         var cb2 = {
		       success: function(d) { 
			       var o = GAME.evalResponse(d.responseText);
			 if(parseInt(o.result) == 1){
               //msg usr has been reported
             }else if(parseInt(o.result) == 2){
             }else{
			         //error reporting
               //GAME.alert(o.msg);
			   
             }
		       },
		       failure: function(d) { },
		       scope: this
	       };
	      var args = 'user_id='+user_id; //todo: other arguments
        YAHOO.util.Connect.asyncRequest('POST', '/report/submit_report.php?'+args, cb2, null);
     }
     
		  var dialog = GAME.openForm({
			id: 'report-user',
			body: d,
			width: '400px',
			title: 'Report User',
			fixedcenter: true,
			constraintoviewport: false,
			buttons: [
			  {text: 'Report', handler: function(){this.submit();this.destroy();}, isdefault: false},
			  {text: 'Close', handler: function(){ this.destroy(); }, isdefault: true}
			],
			deleteOp:true
		  });
		  
		  dialog.callback.success = function(d){
			var code = parseInt(d.responseText);
			if(code == 1) {
				GAME.alert('Thanks.  We will investigate');
			}
			else if(code == 2) {
				GAME.alert('This user cannot be reported');
			}
		  }
		  dialog.callback.failure = function(d){
		  	GAME.alert('Failure at airport');
	  	}
	  	dialog.validate = function(){
	  		return true;	
	  	}
	}
	GAME.getPage('/report/report_form.php?user_id='+user_id+'&type='+type+'&reference='+reference, cb);
}

/***********************************************************
*
* Magazine functions
*
************************************************************/
var MAGAZINE_WINDOW = '';
var VOGUE_WINDOW = '';

GAME.openMagazineWindow = function(issue){
	if(issue == undefined)
    issue = '';
	
	var cb = function(d){
		 MAGAZINE_WINDOW = GAME.openForm({
			id: 'magazine-window',
			body: d,
			width: '726px',
			title: ' ',
			fixedcenter: false,
			xy: [80, 60],
			constraintoviewport: false,
			buttons: [
			
			],
			deleteOp:true
		});
		var ToolTip=YAHOO.widget.Tooltip;
		 var id_names = [
						 "magazine_close_btn_wrapper",
						 "magazine_minimize_btn_wrapper",
						 ];
		 
		 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 } ); 			
		});
		// used to hide certain elements on the gameboard
		GAME.hideElements('cafe');
	}
	GAME.getPage('/magazine/mainwindow.php?issue='+issue, cb);
}
GAME.closeMagazineWindow = function(){
	GAME.showElements('cafe');

	MAGAZINE_WINDOW.destroy();
}
GAME.minimizeMagazineWindow = function(){
  full = document.getElementById('magazine_panel');
  min = document.getElementById('magazine_panel_minimized');
  
  var attributes = { 
	height: { to: 50 } 
  }; 
  var rollup = new YAHOO.util.Anim('magazine_panel', attributes);
  rollup.animate();
  
  GAME.showElements('cafe');

  // subscribe to the onComplete of the minification
  rollup.onComplete.subscribe(function() { 
	full.style.display = "none";	
	min.style.display = "block";
  }); 
  
}
GAME.restoreMagazineWindow = function(){
  full = document.getElementById('magazine_panel');
  min = document.getElementById('magazine_panel_minimized');
  full.style.display = "block";
  min.style.display = "none";
  
  var attributes = { 
	height: { to: 502 } 
  }; 
  var rolldown = new YAHOO.util.Anim('magazine_panel', attributes);
  rolldown.animate();
  
  GAME.hideElements('cafe'); 
}


GAME.magazineLoadPage  = function(issue, page) {
     
    var cb = {
		success: function(d) { 
			document.getElementById('magazine-contents').innerHTML = d.responseText;
		},
		failure: function(d) { },
		scope: this
	};
    GAME.trackPageView("/magazine/getPage.php");
    // history missing
  YAHOO.util.Connect.asyncRequest('GET', '/magazine/getPage.php?issue='+issue+'&page='+page, cb, null);

}

GAME.magazineTrackAdClick = function(ad_id){
   var cb = {
		success: function(d) { },
		failure: function(d) { },
		scope: this
	};
  YAHOO.util.Connect.asyncRequest('GET', '/magazine/trackAdClick.php?ad_id='+ad_id, cb, null);

}

GAME.magazineTryOpen = function(issue){
  if(issue == undefined)
    issue = '';
  // checks to see if we own the requested issue.  if we do, let us read it.  
  // if not, prompt us to buy it
    var cb = {
		success: function(d) { 
			code = parseInt(d.responseText);
			if(code == 1){
        GAME.openMagazineWindow(issue);
      }else{
        GAME.magazineBuyDialogue(issue);
      }
		},
		failure: function(d) { },
		scope: this
	};
  YAHOO.util.Connect.asyncRequest('GET', '/magazine/checkOwn.php?issue='+issue, cb, null);
}

GAME.magazineBuyDialogue = function(issue){
  if(issue == undefined)
    issue = '';
    
  var cb = function(d){
    //for some reason trybuy is getting fired automatically.. not sure why
     var trybuy = function(issue){
         var cb2 = {
		       success: function(d) { 
			       var o = GAME.evalResponse(d.responseText);
			       if(parseInt(o.result) == 1){
               GAME.openMagazineWindow(issue);
             }else{
				GAME.buyFashionBuckz(o.msg);
               //GAME.alert(o.msg);
			   //alert('test');
             }
		       },
		       failure: function(d) { },
		       scope: this
	       };
        YAHOO.util.Connect.asyncRequest('GET', '/magazine/buyIssue.php?issue='+issue, cb2, null);
     }
     
		 MAGAZINE_WINDOW = GAME.openForm({
			id: 'magazine-Purchase',
			body: d,
			width: '300px',
			title: 'Purchase Magazine Issue',
			fixedcenter: true,
			constraintoviewport: false,
			buttons: [
			  {text: 'Buy', handler: function(){trybuy(issue);this.destroy();}, isdefault: false},
			  {text: 'Close', handler: function(){ this.destroy(); }, isdefault: true}
			],
			deleteOp:true
		});
	}
	GAME.getPage('/magazine/buyDialogue.php?issue='+issue, cb);
}

GAME.voguemagazineTryOpen = function() {
	var cb = function(d){
    //for some reason trybuy is getting fired automatically.. not sure why
     
		VOGUE_WINDOW = GAME.openForm({
			id: 'teen-vogue',
			body: d,
			width: '456px',
			title: 'Teen Vogue',
			fixedcenter: false,
			constraintoviewport: false,
			buttons: [
			  {text: 'Close', handler: function(){ this.destroy(); }, isdefault: true}
			],
			deleteOp:true
		});
	}
	GAME.getPage('/magazine/vogue_magazine.php', cb);
}

/*******************************************
*
* Ads functions for magazine
*
*******************************************/
// ADS FUNCTIONS
GAME.ads = function(args){
    GAME.trackPageView("/data/ads/browse.php");
    // history missing
	GAME.loadPanel('data/ads/browse.php', 'W', function() {
		GAME.ads.size = 'whole';
		GAME.ads.image_url = '';
		GAME.ads.headline_container_color = 'rgb(255, 255, 255)';
		GAME.ads.design_type = 1;
		GAME.ads.current_menu = 'headline';
		var dd = new YAHOO.util.DD('headline_div');
		var dd = new YAHOO.util.DD('tagline_div');
		var dd = new YAHOO.util.DD('bodycopy_div');
		var dd = new YAHOO.util.DD('model');
		var dd = new YAHOO.util.DD('design_container');
		var dd = new YAHOO.util.DD('store');
		var dd = new YAHOO.util.DD('player_logo');
		
		GAME.ads.get_design(0);
		
	});
}

GAME.ads.display_border = function(item, on) {
	if (on == true) {
		item.style.border = '1px dashed red';
		item.style.margin = '-1px -1px';
	}
	else {
		item.style.border = 'none';
		item.style.margin = '0px 0px';
		//$('dummy').focus();
		$("ads").focus();
	}
}

// update color
GAME.ads.set_color = function(id, color) {
	if (id == 'headline_container') {
		GAME.ads.headline_container_color = color;
		$(id).style.backgroundColor = color;
		$('background_radio').src = '/images/ads/checked.png';
		$(id).style.backgroundImage = '';
		$('background_custom_radio').src = '/images/ads/unchecked.png';
	}
	else {
		$(id).style.color = color;
	}
}
// update text
GAME.ads.update_text = function(id) {
	$(id).style.fontFamily = $(id+'_font').value;
	$(id).style.fontSize = $(id+'_size').value+'px';
}


//design
GAME.ads.set_design = function(image) {
	$('design').src = image;
}

GAME.ads.set_design_type = function(type) {
	GAME.ads.design_type = type;
	GAME.ads.get_design(0);
}


GAME.ads.get_design = function(page) {
	var cb = function(d){
		$('design_choices').innerHTML = d;
	}
	GAME.getPage('/data/ads/data.php?page='+page+'&size='+GAME.ads.size+'&type='+GAME.ads.design_type, cb);	
}

GAME.ads.toggle_design_size = function() {
	var cb = function(d){
		$('design').src = d;
	}
	GAME.getPage('/data/ads/data.php?design=1&size='+GAME.ads.size+'&image='+$('design').src, cb);
}


GAME.ads.set_size = function(args, image) {
	if (args == 'whole') {
		$('headline_container').style.height = '432px';
		$('tab_full').src = '/images/ads/right-top-full.png';
		$('tab_half').src = '/images/ads/right-top-half-s.png';
		$('ad_cost').innerHTML = 2000;
		if ($('ad_model_image') != undefined) {
			$('ad_model_image').src = '/assets/models/model3.png';
			$('ad_model_image').width=136;
			
		}
	}
	else {
		$('headline_container').style.height = '216px';
		$('tab_full').src = '/images/ads/right-top-full-s.png';
		$('tab_half').src = '/images/ads/right-top-half.png';
		$('ad_cost').innerHTML = 1600;
		if ($('ad_model_image') != undefined) {
//			$('ad_model_image').src = '/assets/models/model3_shrunk.png';
			$('ad_model_image').src = '/assets/models/model3.png';
			$('ad_model_image').width=68 ;			
		}
		
		//make sure nothing gets hidden when switching to half page mode.  bit of a hack but good enough i guess
		if ($('player_logo').offsetTop > 130) {
			$('player_logo').style.top = '-130px';
		}
		
		if($('bodycopy_div').offsetTop  > 130){
      $('bodycopy_div').style.top = '7px;';
    }
    
    if($('headline_div').offsetTop  > 130){
      $('headline_div').style.top = '137px;';
    }
    
    if($('tagline_div').offsetTop  > 130){
      $('tagline_div').style.top = '97px;';
    }
	}
	
	if ($('store_image') != undefined) {
	
		$('store_image').src = image;
		
		if (args == 'whole') {
			$('store').style.left = 0;
			$('design_container').style.top = '-400px';
			$('store').style.top = '-275px';
		}
		else {
			$('store').style.left = 0;
			$('design_container').style.top = '-400px';
			$('store').style.top = '-275px';
		}
	}
	
	GAME.ads.size = args;

	GAME.ads.get_design(0);
	
	GAME.ads.toggle_design_size();
	
}

GAME.ads.menu_toggle = function(args, menu) {
	if (GAME.ads.toggle_visibility_pressed == true) {
		GAME.ads.toggle_visibility_pressed = false;
		return true;
	}
	$('img_'+GAME.ads.current_menu).style.backgroundImage = "url('/images/ads/menu-"+GAME.ads.current_menu+".png')";
	$('img_'+menu).style.backgroundImage = "url('/images/ads/menu-"+menu+"-s.png')";
	GAME.ads.current_menu = menu;
	
	$('ads_edit_headline').style.display = 'none';
	$('ads_edit_tagline').style.display = 'none';
	$('ads_edit_bodycopy').style.display = 'none';
	$('ads_edit_background').style.display = 'none';
	$('ads_choose_design').style.display = 'none';
	$('ads_choose_store').style.display = 'none';
	$('ads_upload_background').style.display = 'none';
	$('ads_edit_logo').style.display = 'none';

	$(args).style.display = 'inline';
	
	if (args == 'ads_choose_design') {
		if ($('model') != undefined) {
			$('model').style.visibility = 'visible';
		}
		$('design_container').style.visibility = 'visible';
	}
	
	
}
GAME.ads.publish = function(args) {
	
	GAME.ads.create_image_url();
	
	var cb = function(d){
		if (d == 0) {
			var dialog = GAME.dialog({
				id: 'page',
				body: 'You can only publish 1 ad per day.',
				width: '200px',
				title: 'Sorry',
				fixedcenter: true,
				buttons: [
				  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
				]});					
		}
		else {
			var dialog = GAME.dialog({
				id: 'page',
				body: 'Congratulations!  Your ad will appear in next edition of our magazine!  The magazine will be available on '+d+'.',
				width: '400px',
				title: 'Success',
				fixedcenter: true,
				buttons: [
				  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
				]});
		}
	}
	GAME.ads.create_image_url();
	GAME.getPage('/data/ads/create.php?'+GAME.ads.image_url, cb);	

}

GAME.ads.create_image_url = function(args) {
	var txt = 'type='+GAME.ads.size;
	
	txt += '&bgcolor='+escape(YAHOO.util.Dom.getStyle('headline_container', 'backgroundColor'));
	txt += '&bgimage='+YAHOO.util.Dom.getStyle('headline_container', 'backgroundImage');
	txt += '&bgtile='+YAHOO.util.Dom.getStyle('headline_container', 'backgroundRepeat');
	
	if ($('model') != undefined) {
	
		if (YAHOO.util.Dom.getStyle('model', 'visibility') != 'hidden') {
			txt += '&model_image='+$('ad_model_image').src;
			txt += '&model_image_w='+$('ad_model_image').width;
			txt += '&model_image_x='+$('model').offsetLeft;
			txt += '&model_image_y='+$('model').offsetTop;
		}
	}
	if (YAHOO.util.Dom.getStyle('design', 'visibility') != 'hidden') {
		txt += '&design='+$('design').src;
		txt += '&design_x='+$('design_container').offsetLeft;
		txt += '&design_y='+$('design_container').offsetTop;
	}
	
	
	//store
	if ($('store') != undefined && YAHOO.util.Dom.getStyle('store', 'visibility') != 'hidden') {
		txt += '&store='+$('store_image').src;
		txt += '&store_x='+$('store').offsetLeft;
		txt += '&store_y='+$('store').offsetTop;
	}
	
	
	
	//headline
	txt += '&headline_x='+$('headline_div').offsetLeft;
	txt += '&headline_y='+$('headline_div').offsetTop;
	txt += '&headline_height='+YAHOO.util.Dom.getStyle('headline', 'height');
	txt += '&headline_text='+((YAHOO.util.Dom.getStyle('headline', 'visibility') == 'hidden') ? '' : $('headline').value);
	txt += '&headline_font='+YAHOO.util.Dom.getStyle('headline', 'font-family');
	txt += '&headline_size='+YAHOO.util.Dom.getStyle('headline', 'font-size');
	txt += '&headline_color='+YAHOO.util.Dom.getStyle('headline', 'color');	
	
	//tagline
	if (YAHOO.util.Dom.getStyle('tagline', 'visibility') == 'visible') {
		txt += '&tagline_x='+$('tagline_div').offsetLeft;
		txt += '&tagline_y='+$('tagline_div').offsetTop;
		txt += '&tagline_height='+YAHOO.util.Dom.getStyle('tagline', 'height');
		txt += '&tagline_text='+$('tagline').value;
		txt += '&tagline_font='+YAHOO.util.Dom.getStyle('tagline', 'font-family');
		txt += '&tagline_size='+YAHOO.util.Dom.getStyle('tagline', 'font-size');
		txt += '&tagline_color='+YAHOO.util.Dom.getStyle('tagline', 'color');	
	}
	
	//bodycopy
	if (YAHOO.util.Dom.getStyle('bodycopy', 'visibility') == 'visible') {
		txt += '&bodycopy_x='+$('bodycopy_div').offsetLeft;
		txt += '&bodycopy_y='+$('bodycopy_div').offsetTop;
		txt += '&bodycopy_height='+YAHOO.util.Dom.getStyle('bodycopy', 'height');
		txt += '&bodycopy_text='+$('bodycopy').value;
		txt += '&bodycopy_font='+YAHOO.util.Dom.getStyle('bodycopy', 'font-family');
		txt += '&bodycopy_size='+YAHOO.util.Dom.getStyle('bodycopy', 'font-size');
		txt += '&bodycopy_color='+YAHOO.util.Dom.getStyle('bodycopy', 'color');	
	}
	
	//player logo
	if (YAHOO.util.Dom.getStyle('player_logo', 'visibility') == 'visible') {
		txt += '&player_logo=1';
		txt += '&player_logo_x='+$('player_logo').offsetLeft;
		txt += '&player_logo_y='+$('player_logo').offsetTop;

		txt += '&player_logo_bgcolor='+YAHOO.util.Dom.getStyle('player_logo_bg', 'backgroundColor');
		txt += '&player_logo_bgimage='+YAHOO.util.Dom.getStyle('player_logo_bg', 'backgroundImage');
		txt += '&player_logo_bordercolor='+$('logo_border_color').value;
		
		txt += '&player_logo_color='+YAHOO.util.Dom.getStyle('player_logo_bg', 'color');
		txt += '&player_logo_font='+YAHOO.util.Dom.getStyle('player_logo_text', 'font-family');
		txt += '&player_logo_size='+YAHOO.util.Dom.getStyle('player_logo_text', 'font-size');
		txt += '&player_logo_width='+YAHOO.util.Dom.getStyle('player_logo', 'width');
		txt += '&player_logo_height='+YAHOO.util.Dom.getStyle('player_logo', 'height');
		txt += '&player_logo_text='+$('player_logo_text').innerHTML;
		
	}	
	
	//cost
	txt += '&ad_cost='+$('ad_cost').innerHTML;	
	GAME.ads.image_url = txt;
	
}

GAME.ads.set_logo_size = function(size) {
	switch(size) {
		case 'small':
			$('player_logo').style.width = '40px';
			$('player_logo').style.height = '40px';
			$('player_logo_bg').style.width = '40px';
			$('player_logo_bg').style.height = '40px';
			$('player_logo_text').style.width = '40px';
			$('player_logo_text').style.height = '40px';
			$('player_logo_text').style.fontSize = $('logo_text_size').value+'px';
		break;
		case 'medium':
			$('player_logo').style.width = '80px';
			$('player_logo').style.height = '80px';
			$('player_logo_bg').style.width = '80px';
			$('player_logo_bg').style.height = '80px';
			$('player_logo_text').style.width = '80px';
			$('player_logo_text').style.height = '80px';		
			$('player_logo_text').style.fontSize = $('logo_text_size').value * 2+'px';
		break;
		case 'large':
			$('player_logo').style.width = '120px';
			$('player_logo').style.height = '120px';
			$('player_logo_bg').style.width = '120px';
			$('player_logo_bg').style.height = '120px';
			$('player_logo_text').style.width = '120px';
			$('player_logo_text').style.height = '120px';		
			$('player_logo_text').style.fontSize = $('logo_text_size').value * 3+'px';
		break;
	}
}


GAME.ads.preview = function(){
	
	var cb = function(d){
		var dialog = GAME.dialog({
			id: 'page',
			body: d,
			width: '670px',
			title: 'Ads preview',
			xy: [80, 100],
			buttons: [
			  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
			]});
	}
	GAME.ads.create_image_url();
	GAME.getPage('/data/ads/create.php?'+GAME.ads.image_url+'&preview=1', cb);
}

GAME.ads.upload_background = function() {
	var uploadHandler = {
		upload: function(o) {
			$('upload_background_holder').innerHTML = o.responseText;
			GAME.ads.set_background($('uploaded_background_src').src, true);
			$('background_custom_radio').src = '/images/ads/checked.png';
		}
	};
	YAHOO.util.Connect.setForm('testForm', true);
	YAHOO.util.Connect.asyncRequest('POST', '/data/ads/upload.php', uploadHandler);
}

GAME.ads.set_background = function(args, go) {
	if (go == true) {
		$('headline_container').style.backgroundColor = '';
		$('headline_container').style.backgroundImage = "url('"+args+"')";
		$('background_radio').src = '/images/ads/unchecked.png';
	}
	else {
		$('headline_container').style.backgroundImage = '';
	}
}

GAME.ads.tile_background = function() {
	$('headline_container').style.backgroundRepeat = ($('ads_background_tile').checked) ? 'repeat' : 'no-repeat';
}

GAME.ads.toggle_visibility = function(image, element) {
	var str = image.src;
	if (element == 'background') {
		if (str.indexOf('unchecked.png') > 0) {
			$('headline_container').style.backgroundColor = GAME.ads.headline_container_color;
			image.src = '/images/ads/checked.png';
			$('background_custom_radio').src = '/images/ads/unchecked.png';
			$('headline_container').style.backgroundImage = '';
		}
		else {
			$('headline_container').style.backgroundColor = 'rgb(255, 255, 255)';
			image.src = '/images/ads/unchecked.png';
		}
	}
	else if (element == 'background_custom') {
		if (str.indexOf('unchecked.png') > 0) { 
			if ($('uploaded_background_src') != undefined) {
				GAME.ads.set_background($('uploaded_background_src').src, true);
			}
			$('background_radio').src = '/images/ads/unchecked.png';
			image.src = '/images/ads/checked.png';
		}
		else {
			if ($('uploaded_background_src') != undefined) {
				GAME.ads.set_background($('uploaded_background_src').src, false);
			}
			image.src = '/images/ads/unchecked.png';
		}
	}
	else {
		if (YAHOO.util.Dom.getStyle(element, 'visibility') == 'visible') {
			image.src = '/images/ads/unchecked.png';
			$(element).style.visibility = 'hidden'; 
		}
		else {
			image.src = '/images/ads/checked.png';
			$(element).style.visibility = 'visible'; 
		}
	}
	
	GAME.ads.toggle_visibility_pressed = true;
}

//check if user has enough fbz
GAME.ads.validate_publish = function(args) {
	var cb = function(d){
		//not enough in the bank
		if  (d == 0) {
			GAME.buyFashionBuckz('You do not have enough fashion bucks to publish the ad');
		}
		else if (d == 1) {
			var dialog = GAME.dialog({
				id: 'page',
				body: 'You can only publish 1 ad per month.  Be sure to check the magazine we see your ad!',
				width: '500px',
				title: 'Sorry',
				fixedcenter: true,
				buttons: [
				  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
				]});					
		}
		else {
//			$('balance').innerHTML = d;
			GAME.ads.publish();
		}
	}
	GAME.getPage('/data/ads/data.php?validate=1&size='+GAME.ads.size, cb);	
}

GAME.ads.toggle_bg = function(id, img, tip_id, tip) {
	if (id != 'img_'+GAME.ads.current_menu) {
		$(id).style.backgroundImage = "url('"+img+"')";
	}
	if (tip_id != '' && tip != '') {
		GAME.ads.tooltip(tip_id, tip); 
	}
}

GAME.ads.toggle_image = function(id, img, tip_id, tip) {	
	$(id).src = img;
}

GAME.ads.tooltip = function(id, tip) {
	if (id == 'tip_head') {
		var tt1 = new YAHOO.widget.Tooltip("tt1", { context:id, text:tip }); 
	}
	if (id == 'tip_line') {
		var tt2 = new YAHOO.widget.Tooltip("tt2", { context:id, text:tip }); 
	}
	if (id == 'tip_body') {
		var tt3 = new YAHOO.widget.Tooltip("tt3", { context:id, text:tip }); 
	}
	if (id == 'tip_ad') {
		var tt4 = new YAHOO.widget.Tooltip("tt4", { context:id, text:tip }); 
	}
	if (id == 'tip_store') {
		var tt5 = new YAHOO.widget.Tooltip("tt5", { context:id, text:tip }); 
	}
	if (id == 'tip_bg') {
		var tt6 = new YAHOO.widget.Tooltip("tt6", { context:id, text:tip }); 
	}
	if (id == 'tip_ubg') {
		var tt7 = new YAHOO.widget.Tooltip("tt7", { context:id, text:tip }); 
	}
}

/*********************************************
*
* Marketing Functions
*
*********************************************/
GAME.fashionNews = function(){
	
	GAME.modal('This features is not yet available', 'Notice');
}

GAME.fashionMagazine = function(){
	
	var cb = function(d){
		var dialog = GAME.dialog({
			id: 'page',
			body: d,
			width: '670px',
			title: 'Fashion News',
			xy: [80, 100],
			buttons: [
			  /*{ text: 'Advertise Here', handler: function(){ 
				this.destroy();
				
			}, isdefault: false },
				*/
			  { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true }
			],
			deleteOp:true
		});
	}
	GAME.getPage('data/magazine.php', cb);
}
GAME.sendCatalog = function(id){
}

GAME.sendCatalogToFriend = function(id){
	
	var cb = {
		success: function(d){
			if (parseInt(d.responseText) == 1) { 
				url = "data/messages/send.php";
				var cb = function(d){
					var dialog = GAME.openForm({
						id: 'send-to-friend-dialog',
						body: d,
						width: '400px',
						title: 'Send to a friend',
						xy: [160, 200],
						buttons: [
						{ text: 'Send', handler: function(){ this.submit() }, isdefault: false },
						{ text: 'Cancel', handler: function(){ this.destroy(); }, isdefault: true }
						],
						deleteOp:true
					});
					
					dialog.callback.success = function(d){
	
						switch(d.responseText){
							case('-10'):	GAME.alert('User does not exist.');	
							break;
							case('1'):		GAME.alert('Catalog Sent');	
							break;
						default:
						} 
					}
	
					dialog.callback.failure = function(d){
						GAME.alert('Failure adding friend');
					}
				}
				GAME.getPage('data/designer/sendtoafriend.php?catalog_id=' + id, cb);
			}
			else {
				GAME.alert("Sorry, you need to add friends before you can send messages!");
			}
		},
		failure: function(d){}
	};				
	YAHOO.util.Connect.asyncRequest('GET', 'api.php?action=has-friends', cb);
}

GAME.sendMyCatalog = function(to){
	
	var cb = function(d){
		var dialog = GAME.openForm({
			id: 'send-mycatalog-dialog',
			body: d,
			width: '400px',
			title: 'Send My Catalog',
			xy: [160, 200],
			buttons: [
			   { text: 'Send', handler: function(){ this.submit() }, isdefault: false },
			   { text: 'Cancel', handler: function(){ this.destroy(); }, isdefault: true }
			 ]
		});
		dialog.callback.success = function(d){
			switch(d.responseText){
				case('-10'):	GAME.alert('User does not exist.');	
				break;
				case('1'):		GAME.alert('Catalog Sent');	
				break;
				default:
			} 
		}
		dialog.callback.failure = function(d){
			GAME.alert('Failure adding friend');
		}
	}
	GAME.getPage('data/designer/sendmycatalog.php?to=' + to, cb);
	
}


GAME.catalog = function(){
	
	var cb = function(d){
		var dialog = GAME.dialog({
					id: 'view-mycatalog-dialog',
					body: d,
					width: '670px',
					title: 'My Design Catalog',
					xy: [80, 100],
					buttons: [
					   { text: 'Close', handler: function(){ this.destroy(); }, isdefault: true },
					   { text: 'Send to a Friend...', handler: function(){  }, isdefault: false }
					 ],
					deleteOp:true
				});
	}
	GAME.getPage('data/designer/mydesigns.php', cb);
}

GAME.viewDesignerCatalog = function(id){

	if(isIE) GAME.allowNav();

	var browserCheck = navigator.userAgent.toLowerCase();

	if ( (browserCheck.search(/mac\sos\sx/)!=-1) && (browserCheck.search(/firefox/)!=-1) ) {
		var d = "<div style='height:90px;width:auto;border-bottom:1px solid #C0C0C0'><b>Problem</b><br /><br />Sorry, but the designer catalog is unable to display properly in Firefox on a Macintosh.<br /></div>";
		
		var dialog = GAME.dialog({
			id: 'catalog-error',
			body: d,
			width: '350px',
			title: 'Design Catalog',
			xy: [80, 100],
			modal: true,
			draggable: false,
			buttons: [
			    { 	text: 'Close', 
			   		handler: 
						function() { 
							this.destroy(); 
						}, 
					isdefault: true 
				}
			 ],
			deleteOp:true
		});
	}
	else {
		
		var cb = function(d){

			var bb = '<div id="designerCatalog" style="">Loading...</div>';
			var swf = "/lib/pageflip/flippingBook.swf";
			var so = new SWFObject(swf, "designerCatalog", "660", "500", "8", '#FFFFFF');
			so.addParam('wmode', 'transparent');
			so.addParam('quality', 'high');
			so.addParam('scale',  'scale');
			so.addParam('flashVars', "xmlConfig=data/designer/catalog.xml.php?id=" + id + "&bgImage=/images/bookbg.jpg");
			
			//var b = '';//fo.getSWFHTML();
			
			var dialog = GAME.dialog({
				id: 'view-catalog-dialog',
				body: d,
				width: '670px',
				title: 'Design Catalog',
				xy: [80, 100],
				modal: true,
				draggable: false,
				buttons: [
					{ 	text: 'Close', 
						handler: 
							function() { 
								if (!isIE) {
									/*try {
									if (typeof($('friends-list')) != "undefined")
										$('friends-list').style.display='block'; 
									if (typeof($('messages-inbox')) != "undefined")
										$('messages-inbox').style.display='block';
									if (typeof($('view-catalog-dialog_c').nextSibling) != "undefined")
										$('view-catalog-dialog_c').nextSibling.style.display='block';										
									} 
									catch(e) {}
                                    */
								}
								GAME.preventNav();
								this.destroy(); 
							}, 
						isdefault: true 
					},
					{ 	text: 'Send to a Friend...', 
						handler: 
							function() { 
							/*	if (!isIE) {
									if (typeof($('friends-list')) != "undefined")
										$('friends-list').style.display='block'; 
									if (typeof($('messages-inbox')) != "undefined")
										$('messages-inbox').style.display='block';
									if (typeof($('view-catalog-dialog_c').nextSibling) != "undefined")
										$('view-catalog-dialog_c').nextSibling.style.display='block';										
								}
                                */
								this.destroy(); 
								GAME.sendCatalogToFriend(id); 
							}, 
						isdefault: false 
					}
				 ],
				deleteOp:true
			});
			
			var cbe = function(){
				//document.getElementById('airportanimation').innerHTML ='asdasdasdasd';
				//alert(document.getElementById('airportanimation').innerHTML);
				//dialog.style.display='none';
				so.write($("designerCatalog"));
				
				// check for windows underneath this...
				// this is a hack to fix FF
				if (!isIE) { 
					$('view-catalog-dialog_c').nextSibling.style.display='none';		
					$('friends-list').style.display='none';
					$('messages-inbox').style.display='none';
				}
			}
			dialog.changeBodyEvent.subscribe(cbe, dialog);
			dialog.setBody(bb);
		}
		GAME.getPage('data/designer/catalog.php?id=' + id, cb);
	}
}
/*********************************************************
*
* Messaging
*
*********************************************************/
GAME.mailBox = function(){
    GAME.hasNextMessagePage = false;
    GAME.trackPageView("/data/messages/mailbox.php");
    
    GAME.process_history({'id':0,'where':'mailBox'});

	GAME.messageOrderBy = 'date';
	GAME.messageSort = 'desc';
	GAME.messageTypeFilter = 0;
	GAME.messageSearch = '';
    
    GAME.loadPanel('data/messages/mailbox.php', 'C', function() {
		if (document.delete_message_form.hasnextpage.value) {
			GAME.hasNextMessagePage = true;
		}
		document.getElementById('header-arrow-'+GAME.messageOrderBy).src = "images/mailbox/sort-arrow-"+GAME.messageSort+".png";
		document.getElementById('header-arrow-'+GAME.messageOrderBy).style.display = "inline";
    });
    GAME.messagePagination = 0;
}

GAME.mailboxOrder = function(orderby) {
	if (GAME.messageOrderBy == orderby) {
		GAME.messageSort = GAME.messageSort=='asc'?'desc':'asc';
	} else {
		document.getElementById('header-arrow-'+GAME.messageOrderBy).style.display = "none";
		GAME.messageOrderBy = orderby;
		GAME.messageSort = 'desc';
	}
	GAME.refreshInbox();
}

GAME.mailboxFilter = function(elem) {
	GAME.messageTypeFilter = elem.value;
	GAME.refreshInbox();
}

GAME.mailboxSearch = function(searchStr) {
	if (typeof(searchStr) != 'undefined') {
		GAME.messageSearch = searchStr;
	} else {
		GAME.messageSearch = '';
		document.getElementById('mb_search').value = '';
	}
	GAME.refreshInbox();
}

GAME.mailbox = GAME.mailBox;

GAME.refreshInbox = function(start) {
    if (document.delete_message_form) {
		document.delete_message_form.delall.checked = false;
    }
/*    var start_str = '';
    if (start) start_str = '?start='+start;
    else start = 0;

    var url = 'data/messages/inbox.php'+start_str;
*/
    if (!start) start = 0;
	
	var url = 'data/messages/inbox.php?start='+start+'&orderby='+GAME.messageOrderBy+'&sort='+GAME.messageSort+'&filter='+GAME.messageTypeFilter+'&search='+GAME.messageSearch;
    GAME.loadContent(url, 'messages-inbox', function() {

    GAME.trackPageView(url);
    
    GAME.process_history({'id':0,'where':'mailBox'});
    
	if (document.delete_message_form.hasnextpage.value == 1) {
	    document.getElementById('nextBtn').style.display = '';
	    GAME.hasNextMessagePage = true;
	} else {
	    document.getElementById('nextBtn').style.display = 'none';
	    GAME.hasNextMessagePage = false;
	}
    });
    GAME.messagePagination = start;
    if (start > 0) document.getElementById('prevBtn').style.display = '';
    else document.getElementById('prevBtn').style.display = 'none';
	document.getElementById('header-arrow-'+GAME.messageOrderBy).src = "images/mailbox/sort-arrow-"+GAME.messageSort+".png";
	document.getElementById('header-arrow-'+GAME.messageOrderBy).style.display = "inline";
}

GAME.openMessage = function(id){	
	if($('message-'+id+'-icon') != undefined) {
		$('message-'+id+'-icon').src= '/images/mailbox/read.png';
	}
	
	var url = "data/messages/message.php?id=" + id;
	var cb = function(d, data){
		var d = GAME.dialog({
			id: 'view-message-dialog-'+id,
			body: d,
			title: 'Viewing Message',
			fixedcenter: false,
			width: '400px',
			buttons: [
				{ text: 'Reply', handler: function(){ f = document.getElementById('message-'+id+'-from').value; if (f=="") GAME.alert("Sorry, you cannot reply to this system messages."); else {this.destroy(); GAME.sendMessage(f,'','',id); } }, isDefault: false }, 		  
				{ text: 'Delete', handler: function(){ this.destroy(); GAME.deleteMessage(id); }, isDefault: false }, 		  
				{ text: 'Close', handler: function(){ this.destroy() }, isDefault: true } 		  
			],
			deleteOp: true
		});
		//refresh the status bar
		GAME.processTicker();
	}
	GAME.getPage(url, cb);
}

GAME.sendMessage = function(user, subj, msg, mid){
	// we could have user as nothing, which mean bring up send message window with populated freinds list in message header
	// we could have a user who is not a friend 
	// we could have a valid username who is a friend of that current user
	// first we check, if user="";  if so, we must check if this user has any friends, if so, we pop-up 'send message window'
	// if username is not blank, then check that the user is a friend of the current user
	//   - if yes, pop-up send message window,
	//   - if no, pop-up friend request window.
	
	YAHOO.initial_load.container.wait.show();
	
    var me = this,
        isFriend = false,
        hasFriends = false,
        url = "",
        username = ((user!=undefined) && (user!='') ? user : ''),
        subject = ((subj!=undefined) && (subj!='') ? subj : ''),
        message = ((msg!=undefined) && (msg!='') ? msg : ''),
        msgid = ((mid!=undefined) && (mid!='') ? mid : '');
    
    var respHandler = {
        success: function(d) {
            YAHOO.initial_load.container.wait.hide();
            switch(parseInt(d.responseText)) {
                case(-10):  
                        GAME.alert(GAME.constants.ERROR_FRIEND_NOT_EXISTS);
                        break;
                case(-2): // recipient blocked messages from user, error message comes in auto-reply message:
                        try {
                            GAME.refreshInbox();
                        } 
                        catch(e) {
                            //console.error(e)
                        }
                        break;
                case(-1):	
                        GAME.alert(GAME.constants.ERROR_FRIEND_EXISTS_IN_LIST); 
                        break;
                case(1):
                        GAME.alert(GAME.constants.MESSAGE_SUCCESS);	
                        try {
                            GAME.refreshInbox();
                        } 
                        catch(e) {
                            //console.error(e)
                        }
                        break;
                default:
                        GAME.alert(GAME.constants.ERROR_TRY_AGAIN);
                        break;
            }
        },
        failure: function() {
            YAHOO.initial_load.container.wait.hide();
            GAME.alert(GAME.constants.ERROR_TRY_AGAIN);
        }
    }
    
    var sendHandler = function(win) {
        var data = GAME.dialogs['sendmessage-dialog'].getData(),
            exploded = '',
            x = '',
            post = '';

        YAHOO.initial_load.container.wait.show();

        if (data.to === "") {
            GAME.alert(GAME.constants.ERROR_EMPTY_USERNAME);
            return;
        }

        if (data.to instanceof Array) {            
            for (var i=0, len=data.to.length; i<len; i++) {
                if (post.length > 0) {
                    post += '&';		
                }
                post += encodeURIComponent('to[]') + '=' + encodeURIComponent(data.to[i]);
            }
        }
        else {
            post += encodeURIComponent(x) + '=' + encodeURIComponent(data.to[i]);
        }

        for(x in data) {
            if (x === 'to') {
                continue;
            }
                        
            if (post.length > 0) {
                post += '&';		
            }

            post += encodeURIComponent(x) + '=' + encodeURIComponent(data[x]);
        }

        win.destroy(); 
        YAHOO.util.Connect.asyncRequest('POST', 'data/messages/send.php', respHandler, post);
    }
    
    var cb = {
        success: function(d){
            if (parseInt(d.responseText) === 1) { 
                me.hasFriends=true;
                url = "data/messages/send.php?username="+username+"&subject="+subject+"&message="+message+"&msgid="+msgid;
                var cb = function(d){
                    var dialog = GAME.dialog({
                        id: 'sendmessage-dialog',
                        body: d,
                        width: '400px',
                        title: 'Send Message',
                        fixedcenter: false,
                        xy: [260, 160],
                        buttons: [
                            {text: 'Send', handler: function(){ sendHandler(this);}, isDefault: true },
                            {text: 'Cancel', handler: function(){ this.destroy(); }, isDefault: false }
                        ]
                    });
                    
                    YAHOO.initial_load.container.wait.hide();
                }
                GAME.getPage(url, cb);
            }
            else {
                YAHOO.initial_load.container.wait.hide();
                GAME.sendMessageToNonFriend(username);				
            }
        },
        failure: function(d){	
            YAHOO.initial_load.container.wait.hide();
        }
    }
    
	if (username === '') {
		YAHOO.util.Connect.asyncRequest('GET', 'api.php?action=has-friends', cb);
	}
	else { // username is not blank
		// check if username is friend
		YAHOO.util.Connect.asyncRequest('GET', 'api.php?action=is-friend&user='+username, cb);
	}
}

GAME.deleteMessage = function(id, feedback){
	
	if(feedback==undefined || feedback==false){
		var displayFeedback = false;	
	} else {
		var displayFeedback = true;	
	}

    if (!GAME.hasNextMessagePage && !document.delete_message_form.to_delete.length) {
	GAME.messagePagination -= 1;
    }
	
	var post = 'action=d&message='+id;
	var cb = {
		success: function(d){
			switch(d.responseText){
				case('1'):	if(displayFeedback) GAME.alert('Deleted Mesage');
							GAME.refreshInbox(GAME.messagePagination);
				break;
				case('-1'):	if(displayFeedback) GAME.alert('Delete Failed');
				break;
				default:
			}
		},
		failure: function(d){
			
			GAME.alert('Async Request failed in deleteMessage');	
		}
	}
	YAHOO.util.Connect.asyncRequest('POST', 'data/messages/api.php', cb, post);
}




GAME.messageAboutDesigner = function(id){
	
	var cb = function(d){
		var dialog = GAME.openForm({
			id: 'message-to-friend-dialog',
			body: d,
			width: '400px',
			title: 'Send a message about this Designer',
			xy: [160, 200],
			buttons: [
			   { text: 'Send', handler: function(){ this.submit() }, isdefault: false },
			   { text: 'Cancel', handler: function(){ this.destroy(); }, isdefault: true }
			 ]
		});
		dialog.callback.success = function(d){
			switch(d.responseText){
				case('-10'):	GAME.alert('User does not exist.');	
				break;
				case('1'):		GAME.alert('Message Sent');	
				break;
				default:		GAME.alert(d.responseText);
			} 
		}
		dialog.callback.failure = function(d){
			GAME.alert('Failure sending message');
		}
	}
	GAME.getPage('data/friends/messageAboutDesigner.php?designer_id=' + id, cb);
	
}


GAME.messageFriend = function(){
	
	var url = "data/friends/messageFriend.php";
	var cb = function(d){
		var dialog = GAME.openForm({
			id: 'friends-list-dialog',
			body: d,
			width: '200px',
			title: 'Send to Who ?',
			modal: true,
			fixedcenter: false,
			constraintoviewport: true,
			buttons: [
				{ text: 'Close', handler: function(){ this.destroy(); }, isDefault: false }
			]
		});
	}
	GAME.getPage(url, cb);
}

GAME.selectAllMessages = function(toggle) {
    var delboxes = document.delete_message_form.to_delete;
    if (!delboxes) return;
    if (!delboxes.length) {
	delboxes.checked = toggle;
	return;
    }
    for (var i = 0; i < delboxes.length; i++) {
	delboxes[i].checked = toggle;
    }
}

GAME.deleteMassMessages = function(feedback) {
	
    if(feedback==undefined || feedback==false){
		var displayFeedback = false;	
    } else {
		var displayFeedback = true;	
    }

    var delboxes = document.delete_message_form.to_delete;
    var to_delete = Array();

    if (!delboxes) return;
    if (!delboxes.length) {
		delboxes = Array(delboxes);
    }
    
    for (var i = 0; i < delboxes.length; i++) {
	if (delboxes[i].checked) {
	    to_delete.push(delboxes[i].value);
	}
    }

    if (!to_delete.length) {
		GAME.alert("You must select at least one message", "Oops!");
		return;
    }

    var delstr = '';
    for (var i = 0; i < to_delete.length; i++) {
		delstr += '&to_delete[]='+to_delete[i];
    }    

    if (!GAME.hasNextMessagePage && to_delete.length == delboxes.length) {
		GAME.messagePagination -= 1;
    }

    var post = 'action=da'+delstr;
    var cb = {
		success: function(d){
	    if (d.responseText > 0) {
			if(displayFeedback) {
			    GAME.alert('Messages Deleted');
			}
			GAME.refreshInbox(GAME.messagePagination);
	    	} else if (d.responseText == -1) {
				if(displayFeedback) {
		    		GAME.alert('Delete Failed');
				}
	    	}
		},
		failure: function(d){ 
		    GAME.alert('Async Request failed in deleteMessage');
		}
    }
    YAHOO.util.Connect.asyncRequest('POST', 'data/messages/api.php', cb, post);
}

/*********************************************
*
* Friendsship
*
**********************************************/
GAME.requestFriend = function(user){

	var url = 'data/friends/addFriend.php';
	var post = 'friend_name=' + user;
	var cb = {
		success: function(d){
			
			switch(d.responseText){
				case('-30'):    GAME.alert("You cannot request yourself to be your friend.");
				break;
				case('-20'):	GAME.alert('You must be a member to add friends.');	
				break;				
				case('-10'):	GAME.alert('Player does not exist.');	
				break;
				case('-8'):		GAME.alert('Player has denied your previous request');
				break;
				case('-6'):		GAME.alert('A friend request has already been submitted.');
				break;
				case('-1'):		GAME.alert('Player is already on your friends list.');	
				break;
				case(1):
				case('1'):		GAME.alert('Request Sent');
								//GAME.friendsList();	
				break;
				default:		alert(d.responseText);
			} 
		},
		failure: function(){
			
		}
	};
	YAHOO.util.Connect.asyncRequest('POST', url, cb, post);
}
GAME.sendMessageToNonFriend = function(user){
		
	var url = 'data/friends/newFriend.php?friend_name=' + user;
	var cb = function(d){
		
		var dialog = GAME.dialog({
			id: 'addfriend-dialog',
			body: d,
			width: '300px',
			title: 'Add a Friend',
			fixedcenter: true,
			buttons: [
				{ text: 'Request Friend', handler: function(){ this.destroy(); GAME.requestFriend(user); }, isDefault: true },
				{ text: 'Close', handler: function(){ this.destroy() }, isDefault: false }				
			],
			deleteOp:true
		});
		
		dialog.callback.success = function(d){

			switch(d.responseText){
				case('-30'):    GAME.alert("You cannot request yourself to be your friend.");
				break;
				case('-20'):	GAME.alert('You must be a member to add friends.');	
				break;				
				case('-10'):	GAME.alert('Player does not exist.');	
				break;
				case('-8'):		GAME.alert('Player has denied your previous request');
				break;
				case('-6'):		GAME.alert('A friend request has already been submitted.');
				break;
				case('-1'):		GAME.alert('Player is already on your friends list.');	
				break;
				case(1):
				case('1'):		GAME.alert('Request Sent');
								//GAME.friendsList();	
				break;
				default:		alert(d.responseText);
			} 
		},
		dialog.callback.failure = function(d){
			GAME.alert('Failure adding friend');
		}
	};
	GAME.getPage(url, cb);
}

GAME.addFriend = function(user){
	
	if(user!=undefined) var username = user;
	else var username = '';
	
	var url = "data/friends/addFriend.php?username=" + username;
	var cb = function(d){
		
		if(GAME.dialogs['addfriend-dialog']) GAME.dialogs['addfriend-dialog'].destroy();
		
		var dialog = GAME.dialog({
			id: 'addfriend-dialog',
			body: d,
			width: '300px',
			title: 'Add a Friend',
			fixedcenter: true,
			buttons: [
				{ text: 'Request Friend', handler: function(){ this.submit(); this.destroy(); }, isDefault: true }		  
			],
			deleteOp:true
		});
		
		dialog.callback.success = function(d){
			
			switch(d.responseText){
				case('-30'):    GAME.alert("You cannot request yourself to be your friend.");
				break;
				case('-20'):	GAME.alert('You must be a member to add friends.');	
				break;
				case('-10'):	GAME.alert('Player does not exist.');	
				break;
				case('-8'):		GAME.alert('Player has denied your previous request');
				break;
				case('-6'):		GAME.alert('A friend request has already been submitted.');
				break;
				case('-1'):		GAME.alert('Player is already on your friends list.');	
				break;
				case(1):
				case('1'):		GAME.alert('Request Sent');
								//GAME.friendsList();	
				break;
				default:		alert(d.responseText);
			} 
		}
		dialog.callback.failure = function(d){
			GAME.alert('Failure adding friend');
		}
		dialog.validate= function(){
			
			if(dialog.getData().friend_name.length==0){
				GAME.alert('Please enter a username', 'Error');
				return false;	
			} else {
				return true;	
			}
		}
		dialog.registerForm();
	}
	GAME.getPage(url, cb);
}

GAME.friendsList = function(){
	
	var url = "data/friends/friendsList.php";
	var cb = function(d){
		soundManager.play('girls_laughing');
		var dialog = GAME.openForm({
			id: 'friends-list-dialog',
			body: d,
			width: '200px',
			title: 'My Friends',
			fixedcenter: false,
			constraintoviewport: true,
			xy: [827, 100],
			buttons: [
				{ text: 'Add', handler: function(){ GAME.addFriend(); }, isDefault: false },
				//{ text: 'Requests', handler: function(){ GAME.friendsQueue(); }, isDefault: true },
				{ text: 'Close', handler: function(){ this.destroy(); }, isDefault: false }
			],
			deleteOp:true
		});
	}
	GAME.getPage(url, cb);
}

GAME.getOnlineUsers = function(){
	var url = "data/friends/friendsList.php?h=120&oo=1";
	var cb = function(d){
		document.getElementById('online-list').innerHTML = d;
	}
	GAME.getPage(url, cb);
}

GAME.approveFriend = function(rid){

	var url = "data/friends/process.php?a=a&id=" + rid;
	var cb = function(d){
		
//		GAME.friendsList();
		//GAME.friendsQueue();
		GAME.refreshFriendList();
		GAME.refreshInbox();
	}
	GAME.getPage(url, cb);
}

GAME.denyFriend = function(id){
	
	var url = "data/friends/process.php?a=d&id=" + id;
	var cb = function(d){

		GAME.alert('Friendship Denied');
		//GAME.friendsQueue();
	}
	GAME.getPage(url, cb);
}

GAME.blockFriend = function(id){
	
	var url = "data/friends/process.php?a=b&id=" + id;
	var cb = function(d){
		if (parseInt(d) > 0) {
			GAME.alert('You will not receive messages from this buddy');
			GAME.refreshFriendList();
			//GAME.friendsQueue();
		} else {
			GAME.alert('An error occured, try again later!');
		}
	}
	GAME.getPage(url, cb);
}

GAME.unblockFriend = function(id){
	
	var url = "data/friends/process.php?a=u&id=" + id;
	var cb = function(d){
		if (parseInt(d) > 0) {
			GAME.refreshFriendList();
			//GAME.alert('This buddy can keep in touch with you again');
			//GAME.friendsQueue();
		} else {
			GAME.alert('An error occured, try again later!');
		}
	}
	GAME.getPage(url, cb);
}

GAME.refreshFriendList = function() {
	var url = "data/messages/friendlist.php";
	var cb = function(d){
		if (d != "") {
			document.getElementById("friendlist").innerHTML = d;
		}
	}
	GAME.getPage(url, cb);
}

GAME.friendsQueue = function(){
	
	var url = "data/friends/friendsQueue.php";
	var cb = function(d){
		var dialog = GAME.openForm({
			id: 'friends-queue-dialog',
			body: d,
			width: '300px',
			title: 'Friend Requests',
			fixedcenter: false,
			constraintoviewport: true,
			xy: [100, 150],
			buttons: [
				{ text: 'Close', handler: function(){ this.cancel() }, isDefault: false }
			],
			deleteOp:true
		});
		//var tabView = new YAHOO.widget.TabView('friends-queue-tabs');
	}
	GAME.getPage(url, cb);
}

GAME.openRequest = function(id, request_id){
	var url = "data/messages/message.php?id=" + id;

	var cb = function(d){
		var buttons = [];

		buttons[buttons.length] = { text: 'Approve Friend', handler: function(){ GAME.approveFriend(request_id);GAME.deleteMessage(id, false);this.destroy(); }, isDefault: true };
		buttons[buttons.length] = { text: 'Deny Friend', handler: function(){ GAME.denyFriend(request_id);GAME.deleteMessage(id, false);this.destroy(); }, isDefault: false };
		buttons[buttons.length] = { text: 'Close', handler: function(){ this.destroy() }, isDefault: true };
		
		var d = GAME.dialog({
			id: 'view-message-dialog' + id,
			body: d,
			title: 'Friend Request',
			fixedcenter: false,
			width: '400px',
			buttons: buttons,
			deleteOp:true
		});
		
	}
	GAME.getPage(url, cb);
}

GAME.removeFriend = function(friend_id){
	var cb = {
		success: function(obj) { 
			GAME.friendsList();
			GAME.alert('Your friend has been removed from your buddy list'); 
		},
		failure: function(obj) { GAME.alert('FAILURE'); }
	};
	function removeFriend(){
		this.hide();
		var url = "api.php?action=friend-remove&uid=" + friend_id;
		YAHOO.util.Connect.asyncRequest('GET', url, cb);
	}
	var m = GAME.dialog({ 
		id:'removeFriend-dialog',
		title: 'Confrim',
		body: 'Do you really want to remove this friend ?',
		fixedcenter: false,   
		visible: true,  
		modal: false,
		zIndex: 90,
		xy: [150, 280],
		draggable: true, 
		constraintoviewport: true,
		width: '350px',
		buttons: [ 
			{ text:"Remove It", handler: removeFriend, isDefault: false }, 
			{ text:"Close", handler: function() { this.destroy(); }, isDefault: true } 
		]
	});
}

GAME.reportIssue = function(){
	YAHOO.initial_load.container.wait.show();
	var cb = function(data){
		YAHOO.initial_load.container.wait.hide();
		var d = GAME.dialog({
			id: 'bug-report',
			width: '400px',
			title: 'Feedback',
			body: data,
			modal: true,
			fixedcenter: true,
			buttons: [ 
				{text:'Send Report', handler: function(){ this.submit(); }, isDefault: true },
				{text:'Cancel', handler: function(){ this.destroy(); }, isDefault: false }
			],
			deleteOp: true
		});
		d.callback = {
			success: function(){

				GAME.alert('Thank you for your report');
			},
			failure: function(){

			}
		}
		d.validate = function(){
			var data = this.getData();
			if(data.browser == ""){
				GAME.alert("Plase select your browser!");
				return false;
			}
			if(data.data == ""){
				GAME.alert("Please enter problem description!");
				return false;
			}
			return true;
		};
	}
	GAME.getPage('data/debug/form.php', cb);
}

GAME.submitContestEntry = function(id,type){
	switch (type) {
		case 1:
		case 2:
		case 3:
			GAME.submitContestDesign(id);
			break;
		case 4:
			GAME.submitContestStore(id);
			break;
		case 100:
			GAME.submitContestDiva(id);
			break;
		case 200:
			GAME.submitContestDiva(id,'closet');
			break;
		default:
			GAME.alert("Bad contest type");
	}
}

GAME.oneTimeBonus = function(_userid, _bonus, _bonus_ref, _token) {
	var query = {
		token: _token,
		user_id: _userid,
		bonus: _bonus,
		bonus_ref: _bonus_ref
	}; 
	GAME.jsapi.call('bankAccount','oneTimeBonus',query, null, 1);
}

encode_public_id = function(id, type) {
	checksum=0;
	separator='u';
	added_to_id = parseInt(id)+54321;
	strid=id.toString();
	for (i = 0, num_of_chars=strid.length; i < num_of_chars; i++) {
		checksum += parseInt(strid[i]);
	}
	if (type != undefined) {
		switch (type) {
			case 'profile':
				separator='p';
				break;
			case 'store':
				separator='s';
				break;
			case 'showroom':
				separator='h';
				break;
			case 'messages':
				separator='m';
				break;
		}
	}
	
	return added_to_id+separator+checksum;
}

/** Debug class*/
function Debug(){ // constructor
}
Debug.prototype.getResult = function(arg){
	var s = "";
	switch(arg.constructor){
		case Object:
			for(var prop in arg){
				s += "[" + prop + "] : " + arg[prop] + ", ";
			}
			s = s.substring(0, s.lastIndexOf(","));
			break;
		case String:
			s = arg;
			break;
	}
	return s;
};
Debug.prototype.print = function(arg){
	var s = this.getResult(arg);	
	if(console != undefined){
	}else{
		window.alert("RESULT: " + s);
		var div = document.createElement("div");
		div.innerHTML = s;
	}
};
