/* shared.js: shared site functions */

function trackThis(trackingObject)
{
	try
	{
    	switch(trackingObject.type)
    	{
    		case "event":
    			try
				{
					var s = trackingObject.label.split("|");
					pageTracker._trackEvent(s[0], s[1]);
				}
				catch(err){}
    			break;
    		
    		case "page":
    			try
				{
					pageTracker._trackPageview(trackingObject.label);
				}
				catch(err){}
    			break;
    	}
    }
    catch(err){}
}

function showBox(id) {
	var container = $(id);
	if (container) container.show();
}

function hideBox(id) {
	var container = $(id);
	if (container) container.hide();
}

function anchorMove(destination)
{
	var currentHref = location.href;
	location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#" + destination;
}

var tempNav = "";

function toggleMore() {
	if($('more_games').visible())
	{
		$('nav').className = tempNav;
	}else{
		tempNav = $('nav').className;
		$('nav').className = 'more';
		trackThis({type:'event', label:'Top Nav|Top Nav - Expand More'});
	}
	$('more_games').toggle();
}

function toggleAdvancedSearchBox(boxId) {
	toggleBox(boxId, 'giant_search_box');
	if ($(boxId).className.indexOf("_open") >= 0) {
		$("st_advanced_" + boxId).value = $("st_" + boxId).value;
		$("st_" + boxId).hide();
		$("img_" + boxId).hide();
		$("box_top_" + boxId).hide();
	} else {
		$("st_advanced_" + boxId).value = "";
		$("st_" + boxId).show();
		$("img_" + boxId).show();
		$("box_top_" + boxId).show();
	}
}

function selectTab(tabID, contentID, trackingObject)
{
	
	if($(currentGPTab)) { $(currentGPTab).className = ""; }
	$(currentGPContent).hide();
	currentGPTab = tabID;
	currentGPContent = contentID;
	if($(tabID)) $(tabID).className = "current";
	$(contentID).show();
	
	trackThis(trackingObject);
}
                                                                                         
function toggleBox(boxID,boxName)
{
	if($(boxID).className == boxName)
	{
		$(boxID).className = boxName + "_open";
	}else{
		$(boxID).className = boxName;
	}
}

function toggleStyle(styleName)
{
	$$('div[id^=score_]').each(function(e) {e.className = styleName});
	
}

function toggleSearch(styleName)
{
	$$('div[id^=game_result_]').each(function(e) {e.className = styleName});
}

var currentSPTab = "game_tab";

function swapDivAndTab(tabID,divID,styleName)
{
	if(currentSPTab != tabID)
	{                    
		$(divID).className = styleName;
		$(currentSPTab).className = "";
		
		currentSPTab = tabID;
		
		$(currentSPTab).className = "current";
	}
	
}

var currentFeatureImage = "feature_image_1";

function popFeature(featureID,featurePath) {
	$('popUpThumb').src = $("feature_" + featureID).src;
	  
	$('popUpThumbFrame').className = "over_button_" + featureID;
	$('popUpThumbFrame').show();
	//$('popUpThumbFrame').style.left = Event.pointerX(event);
	//$('popUpThumbFrame').style.top = Event.pointerY(event);
	if(currentFeatureImage != 'feature_image_' + featureID)
	{
		
		//$(currentFeatureImage).fade();
		new Effect.Opacity(currentFeatureImage,{from: 1.0, to: 0.0});
		//$('feature_image_' + featureID)
		new Effect.Opacity('feature_image_' + featureID,{from: 0.0, to: 1.0});
		//$('feature_image_' + featureID).Opacity({from: 0.0, to: 1.0});
		currentFeatureImage = 'feature_image_' + featureID;
	}
	
}

function popOutFeature() {
	$('popUpThumbFrame').hide();
}

var currentCSTab = "my_cs_default_module_buffer";
var currentCSContentTab = "my_cs_default_module";

function myCSTab(bufferTabID, contentTabID)
{	
	if(bufferTabID == currentCSTab)
	{
		$(currentCSTab).hide();	
		$(currentCSContentTab).hide();			
                                                                   
		
		
		$("my_cs_default_module_buffer").show();				
		
		$("my_cs_default_module").show();
		
		//$("my_cs_expander").className = "expand";
		
		currentCSTab = "my_cs_default_module_buffer";
		currentCSContentTab = "my_cs_default_module";
	}else{
		$(currentCSTab).hide();	
		$(currentCSContentTab).hide();	
			
		//$("my_cs_expander").className = "close";
				
		$(bufferTabID).show();			
		$(contentTabID).show();
		
		currentCSTab = bufferTabID;
		currentCSContentTab = contentTabID;
		
	}
}

function expandCSTab()
{
	if(currentCSTab == "my_cs_default_module_buffer")
	{
		myCSTab('trophies_module_buffer','trophies_module')
	}else{
		
		myCSTab('my_cs_default_module_buffer','my_cs_default_module')
	}
}

function ImageSwap(imageID, imagePath)
{
	$(imageID).src=imagePath;
}

function popupDialog(contentID,height,width) {	
	
	w = new UI.Window({    
	    id: 	   'popup',
	    width:         width,
	    height:        height,
	    minWidth:      width,
	    minHeight:     height,	
	    shadow: true}).show();
	    w.setContent($(contentID).innerHTML);
	    w.setPosition(100,300);
}

function getClientFlashVersion() {
	var playerVersion = swfobject.getFlashPlayerVersion();
	return playerVersion.major + "." + playerVersion.minor + "." + playerVersion.release; 
}

function showAjaxMessage(msg) {
	$('ajax_popup_content').innerHTML = msg;
	ajaxWindow = new UI.Window({    
	    id: 	   'popup',
	    width:         500,
	    height:        310,
	    minWidth:      500,
	    minHeight:     310,	
	    shadow: true}).show();
	    ajaxWindow.setContent($('ajax_popup').innerHTML);
	    ajaxWindow.center();
	    ajaxWindow.setPosition(100);
}

function showAjaxError() {
	alert("Sorry, an error occurred.");
}

function addGameFavorite(gameId, callback) {

	new Ajax.Request("/ajax/add-favorite", {
		method: "post",
		parameters: {"gameId": gameId},
		onSuccess: function(transport) {
			var jo = transport.responseJSON;
			if (jo.status == "ok") {
				if (callback) {
					callback.callback(jo);
				}
			} else {
				showAjaxError();
			}
		},
		onFailure: function(transport) {
			showAjaxError();
		} 
	});
	
}

function bookmarkGame(url, title) {
	
	var switchCopy = false;
	
	if (!Prototype.Browser.IE && window.sidebar) {
		window.sidebar.addPanel(title, url, "");
		switchCopy = true;
	} else if (Prototype.Browser.IE && window.external) {
		window.external.AddFavorite(url, title);
		switchCopy = true;
	} else {
		alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
	}
	
	if (switchCopy) {
		var li = $$("div#game_header_module ul li.bookmarks");
		if (li && li.length > 0) {
			li[0].update("<a href='#'><span>Bookmarked</span></a>");
		}
	}

}

function removeGameFavorite(gameId, callback) {

	new Ajax.Request("/ajax/remove-favorite", {
		method: "post",
		parameters: {"gameId": gameId},
		onSuccess: function(transport) {
			var jo = transport.responseJSON;
			if (jo.status == "ok") {
				if (callback) {
					callback.callback(jo);
				}
			} else {
				showAjaxError();
			}
		},
		onFailure: function(transport) {
			showAjaxError();
		} 
	});
	
}

function underConstruction() {
	alert("Feature under development.");
}

function refreshCaptcha() {

	var url = "/ajax/refresh-captcha";

	new Ajax.Request(url, {
		method: "get",
		onSuccess: function(transport) {
			var newValue = transport.responseText;
			$("captcha_text").value = newValue;
			$("captcha_image").src = "/captcha?captchaText=" + newValue;
		}
	});
	
}

var leaderHash = new Hash();
var currentUrl;
var currentTab = 0;
var selectedPage = 1;

function selectLeaderboardRange(divId, gameId, index, length, pageSize, page, popup, findMe, hideTrophies, callback) {

	showLoading(divId);
	
	if (index != undefined) currentTab = index;
	if (page != undefined) selectedPage = page;
	
	var buttons = $$("#gamepage_leaderboard .gamepage_info #leaderboard_menu ul li");
	for (var i = 0; i < buttons.length; i++) {
		buttons[i].removeClassName("current");
		if (i == currentTab) buttons[i].addClassName("current");
	}

	var range = "day";
	if (currentTab == 0) {
		range = "day";
	} else if (currentTab == 1) {
		range = "week";
	} else if (currentTab == 2) {
		range = "month";
	} else if (currentTab == 3) {
		range = "all";
	}

	var gameLevel = 0;
	if (document.frmLeaderBoard && document.frmLeaderBoard.gameLevel) {
		gameLevel = document.frmLeaderBoard.gameLevel.value;
	}
	
	var url = "/ajax/leaderboard?id=" + gameId + "&gameLevel=" + gameLevel + "&length=" + length + "&pageSize=" + pageSize + "&range=" + range + "&page=" + selectedPage;
	if (popup) url += "&popup=yes";
	if (findMe) url += "&findMe=yes";
	if (hideTrophies) url += "&showTrophies=no";

	currentUrl = url;

	var content = leaderHash.get(url);
	if (content != null) {
		$(divId).update(content);
		if (callback) callback.callback();
		return;
	}

	new Ajax.Request(url, {
		method: "get",
		onSuccess: function(transport) {
			$(divId).update(transport.responseText);
			leaderHash.set(currentUrl, transport.responseText);
			if (callback) callback.callback();
		}
	});
}

function findMeOnLeaderboard(divId, gameId, length, pageSize, popup, hideTrophies, callback) {
	selectLeaderboardRange(divId, gameId, undefined, length, pageSize, undefined, popup, true, hideTrophies, callback);
}

function showLoading(divId) {
	$(divId).update('<div class="ajax_loader">&nbsp;</div>');
}

function showLeaderboard(gameId) {
	var features = "width=680, height=800, scrollbars=yes, toolbar=no, status=no, noresize";
	window.open("/leaderboard?id=" + gameId, "leaderboard", features);
}

function changeLeaderboardTab(newTab, oldTab, extraButtonFlags)
{
	showBox(newTab + '_leaderboard');
	hideBox(oldTab + '_leaderboard');
	
	$(newTab + '_tab').className='current';
	$(oldTab + "_tab").className='';
	
	if(extraButtonFlags==true)
	{
		$('full_leaderborad_button').show();
		$('my_rank_button').show();
	}else{
		$('full_leaderborad_button').hide();
		$('my_rank_button').hide();
	}
	
}

function popupChallengeHowTo() {
	var features = "width=592, height=490, scrollbars=no, toolbar=no, status=no, noresize";
	window.open("challenge-how-to", "how_to_challenge", features);
}

function showHelp(key) {
	var features = "width=592, height=490, scrollbars=no, toolbar=no, status=no, noresize";
	window.open("/faq-popup?key=" + key, "show_help", features);
}

function popupInviteFB() {
	var features = "width=600, height=600, scrollbars=no, toolbar=no, status=no, noresize";
	window.open("/facebook/invite-friends", "invite_friends", features);
}




function ChangeFavoriteCallback(secondaryCallback) {
	this.secondaryCallback = secondaryCallback;
}
ChangeFavoriteCallback.prototype.callback = function(jo) {
	
	var duplicate = jo.duplicate && jo.duplicate == "yes";
	
	if (!duplicate) {
		
		if ($("top_favorites_module")) {
			new Ajax.Updater("top_favorites_module", "/ajax/top-favorites", {
				method: "get"
			});
		}
		
		if ($("my_candystand_module")) {
	
			var secondaryCallback = this.secondaryCallback;
			
			new Ajax.Request("/ajax/my-candystand", {
				method: "get",
				onSuccess: function(transport) {
					$("my_candystand_module").update(transport.responseText);
					if (secondaryCallback) {
						secondaryCallback.callback(jo);
					}
				}
			});
			
		}
	}
	
	var li = $$("div#game_header_module ul li.favorites");
	if (li && li.length > 0) {
		if (!duplicate) {
			li[0].update("<a href='#'><span>Added to favorites</span></a>");				
		} else {
			li[0].update("<a href='#'><span>One of your Favorites</span></a>");
		}
	}
};

function limitTextArea(textarea, counter, max) {

    var ta = $(textarea);

    if (ta.getValue().length > max)
        ta.setValue(ta.getValue().substring(0, max));
    else
	$(counter).update(max - ta.getValue().length);
}

var miniPersonalFeedHash = new Hash();

function navigateMiniPersonalNewsfeed(page, myCsUserName) {
	
	var content = miniPersonalFeedHash.get(page);
	if (content != null) {
		$("status_update_module").update(content);
		return;
	}

	new Ajax.Request("/ajax/mini-personal-newsfeed", {
		method: "post",
		parameters: {start : page,
            		userName: myCsUserName},
        evalScripts: true,
		onSuccess: function(transport) {
            content = transport.responseText;
            $("status_update_module").update(content);
            miniPersonalFeedHash.set(page, transport.responseText);
        }
	});

};

function toggleLoginButtons(toggleOn,toggleOff)
{
	$(toggleOn + "_button").src = "http://www.candystand.com/assets/images/modules/widgets/" + toggleOn + "_button_on.gif";
	$(toggleOff + "_button").src = "http://www.candystand.com/assets/images/modules/widgets/" + toggleOff + "_button_off.gif";
	$(toggleOn + "_form").show();
	$(toggleOff + "_form").hide();
}