var MBZ_SEP = "_";

$(document).ready(function(){

	// Add event handlers for search tabs
	$("#wallpapers_link").click(function(event){
		$("#search_ringtones_div").css({display:"none"});
		$("#search_wallpapers_div").css({display:"block"});
		$("#wallpapers_q").attr({value:$("#ringtones_q").attr("value")});
		$("#wallpapers_q").select();
		$("#wallpapers_q").focus();
	});

	$("#ringtones_link").click(function(event){
		$("#search_ringtones_div").css({display:"block"});
		$("#search_wallpapers_div").css({display:"none"});
		$("#ringtones_q").attr({value:$("#wallpapers_q").attr("value")});
		$("#ringtones_q").select();
		$("#ringtones_q").focus();
	});

	// Online status
	var pse_sticky = false;
	var pse_stay_closed = false;
	var pse_updating = false;
	var pse_original = null;
	var pse_default  = "Set your online status.";

	// Check no status set
	if($("#pse_txt").val() == "") $("#pse_txt").val(pse_default);

	// Add event handlers for profile status text
	$("#profile_st_edit").bind("mouseenter", function(){
		if(pse_stay_closed === true || pse_updating === true) return;
		$(this).css("background-color", "white");
		$("#pse_ok").css("visibility", "visible");
		$("#pse_cancel").css("visibility", "visible");

	}).bind("mouseleave", function(){
		if(pse_sticky === true) return;
		pse_stay_closed = false;
		$(this).css("background-color", "transparent");
		$("#pse_ok").css("visibility", "hidden");
		$("#pse_cancel").css("visibility", "hidden");
	});

	$("#pse_txt").bind("focus", function(){
		pse_sticky = true;
		if(pse_original == null) pse_original = $(this).val();
		if($(this).val() == pse_default){
			$(this).val("");
		}else{
			$(this).select();
		}

	}).keyup(function(){
		var text = $(this).val();
		var text_len = text.length;
		if(text_len >= 50) $(this).val(text.substr(0, 50));
	});

	$("#pse_cancel").bind("click", function(){
		pse_sticky = false;
		pse_stay_closed = true;
		pse_txt_status(pse_original);
		$("#profile_st_edit").trigger("mouseleave");
	});

	$("#pse_ok").bind("click", function(){
		pse_sticky = false;
		pse_updating = true;
		var new_status = $("#pse_txt").val().substr(0, 50);
		$("#profile_st_edit").trigger("mouseleave");
		$("#pse_txt").val("Updating. Please wait...");
		$.getJSON(make_link("Service", "Update-User-Status"), { New_Status: new_status }, function(data){
			if(data["error"] === true){
				$("#pse_txt").val("Error: " + data["error_code"]);
				return;
			}
			pse_original = data["status_usr"];
			pse_txt_status(pse_original);
			$("#change_me_too").html(pse_original);
			pse_updating = false;
		});
	});

	// Load teaser
	$("#sky_teaser").html('<img id="sky_teaser_img" src="/img/free_ringtones.gif" onload="teaser_anim()" />');
	sel_anim = Math.floor(Math.random() * anim_params.length);
	$("#sky_teaser_img").css(anim_params[sel_anim][0]);
});

var sel_anim = 0;
var anim_params = [
	[{ opacity:0.01, "margin-left":"-200px", width:"200px" }, { opacity: 1, marginLeft: "10px", width: "627px" }],
	[{ opacity:0.01, "margin-left":"637px" , width:"1px"   }, { opacity: 1, marginLeft: "10px", width: "627px" }],
	[{ opacity:0.01 }, { opacity: 1 }],
	[{ opacity:0.01, height:"1px" }, { opacity: 1, height:"44px" }]
];

function teaser_anim(){
	$("#sky_teaser_img").animate(anim_params[sel_anim][1], 1000);
}

function alert_r(obj){
	alert(print_r(obj));
}

function print_r(obj){
	var str = "";
	if(typeof obj != "object") return obj + "";

	for(i in obj){
		str += "[" + i + "] = [" + print_r(obj[i]) + "]\n";
	}
	return str;
}

var img_loaded = false;
function zoom_show(new_img, new_size){

	// Get new_w and new_h
	var tmp = new_size.split("x");
	var new_w = tmp[0];
	var new_h = tmp[1];

	var coords  = $("#w_detail").offset();
	var start_w = $("#thumb_img").width();
	var start_h = $("#thumb_img").height();

	$("#zoom_img").css({
		width   : start_w + "px",
		height  : start_h + "px"
	});

	$("#zoom").css({
		left    : coords.left + "px",
		top     : coords.top  + "px",
		display : "block"
	});

	$("#zoom_img").attr({src: new_img});

	$("#zoom_img").animate({
		width:  new_w + "px",
		height: new_h + "px"
	}, (img_loaded ? 300 : 1000), "linear");
}

function zoom_hide(){
	var start_w = $("#thumb_img").width();
	var start_h = $("#thumb_img").height();

	// Next time animation is faster
	img_loaded = true;

	$("#zoom_img").animate({
		width:  start_w + "px",
		height: start_h + "px"
		}, 300, "linear", function(){
		$("#zoom").css({display: "none"});
	});
}


// Urlencode from php
function urlencode(str){
	var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
	var ret = str.toString();

	var replacer = function(search, replace, str){
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};

	// The histogram is identical to the one in urldecode.
	histogram["!"]   = "%21";
	histogram["%20"] = "+";

	// Begin with encodeURIComponent, which most resembles PHP's encoding functions
	ret = encodeURIComponent(ret);

	for(search in histogram){
		replace = histogram[search];
		ret = replacer(search, replace, ret) // Custom replace. No regexing
	}

	// Uppercase for full PHP compatibility
	return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2){
		return "%" + m2.toUpperCase();
	});

	return ret;
}

// Urldecode from php
function urldecode(str){
	var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
	var ret = str.toString();

	var replacer = function(search, replace, str){
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};

	// The histogram is identical to the one in urlencode.
	histogram["!"]   = "%21";
	histogram["%20"] = "+";

	for(replace in histogram){
		search = histogram[replace]; // Switch order when decoding
		ret = replacer(search, replace, ret) // Custom replace. No regexing   
	}

	// End with decodeURIComponent, which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);

	return ret;
}

function val_enc(val){
	return urlencode(val.toString().replace(/_/g, "¦").replace(/\//g, "%2F"));
}

function val_dec(val){
	return urldecode(val).replace(/¦/g, MBZ_SEP).replace(/%2F/g, "/");
}

// make_link() from php
function make_link(){

	var module = arguments[0];
	var action = arguments[1];
	var parameters = arguments[2];

	if(module == '') module = "Homepage";
	if(action == '') action = "Index";
	
	// Add module
	ret_val = "/" + module;
	if(action == "Index" && parameters == null && parameters.length == 0) return ret_val;
	
	// Add action
	ret_val += MBZ_SEP + val_enc(action);
	if(parameters == null || parameters.length == 0) return ret_val;

	// Add parameters
	for(key in parameters){

		// Skip system params
		if(key == "Module" || key == "Action") continue;

		val = parameters[key];
		ret_val += MBZ_SEP + val_enc(key);
		if(val != null) ret_val += MBZ_SEP + val_enc(val);
	}

	// Safety check
	ret_val = ret_val.replace(/\.\.\//, "[dds]");
	return ret_val;
}


// Debug function usign Firebug Console or alerts
function mbz_debug(message){
	try {
		if(window.console && typeof(window.console.error) === "function" && typeof(window.console.log) === "function"){
			if(typeof(message) === "object" && typeof(message.name) === "string" && typeof(message.message) === "string"){
				window.console.error(message);
			}else{
				window.console.log(message);
			}
		}else{
			if(typeof(message) === "object"){
				alert_r(message)
			}else{
				alert(message)
			}
		}
	}catch(ex){; }
}

function redirect(url){
	location.href = url;
}

function redirect_back(){
	parent.history.back();
}

function pse_txt_status(str){
	if(str == ""){
		$("#pse_txt").val(pse_default);
	}else{
		$("#pse_txt").val(str);
	}
}

function exlnk(url_ex){
	window.external.LaunchBrowser(url_ex + "");
}

// Tooltip funtion
var tooltip = function(){
	var id = "tt";
	var top = 3;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(tit, txt, tier, w){
			if(tt == null){
				tt = document.createElement("div");
				tt.setAttribute("id", id);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = "alpha(opacity=0)";
				document.onmousemove = this.pos;
			}
			tt.style.display = "block";
			tt.innerHTML = "<b>" + tit + "</b>" + txt;

			if(tier){
				tt.className = "tier_" + tier;
			}else{
				tt.className = "tier_0";
			}

			tt.style.width = w ? w + "px" : "auto";
			if(!w && ie){
				tt.style.width = tt.offsetWidth;
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + "px"}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u - h) + "px";
			tt.style.left = (l + left) + "px";
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = "alpha(opacity=" + alpha + ")";
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = "none"}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();

String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g, '');
}


/* ------ Shoutbox ------ */

var sb_last     = 0;
var sb_shouts   = [];
var sb_shouting = false;
var sb_timer    = null;
var sb_interval = 5000;

function check_shouts(){

	// Ajax call
	$.getJSON(make_link("Service", "Shout-Check"), { LastShout: sb_last }, function(data){

		// Update shouts
		if(data["error"] !== true){
			update_shouts(data["shouts"], data["last_shout"]);
		}
	});
}

function update_shouts(new_shouts, last_shout){

	if(new_shouts.length > 0){

		var sb_shouts_len = sb_shouts.length;

		// Update shouts array
		var kk_max = 15 - new_shouts.length;
		for(kk=0; kk<kk_max; kk++){
			if(kk >= sb_shouts_len) continue;
			new_shouts[new_shouts.length] = sb_shouts[kk];
		}
		sb_shouts = new_shouts;
		sb_shouts_len = sb_shouts.length;

		var xhtml = "";
		for(kk=0; kk<sb_shouts_len; kk++){
			xhtml += '<div class="sb_l' + (kk%2 == 0 ? "1" : "2") + '"><span class="sb_d">' + sb_shouts[kk][0] + '</span><span class="sb_u">' + (sb_shouts[kk][1] ? '<a href="' + make_link("Profile", sb_shouts[kk][2]) + '">' + sb_shouts[kk][2] + '<a/>' : sb_shouts[kk][2]) + '</span>:<span class="sb_t">' + sb_shouts[kk][3] + '</span></div>';
		}
		$("#sb_c").html(xhtml);
	}

	// Update last
	sb_last = last_shout;

	// Resume auto-checker
	if(sb_shouting === true) return;
	sb_timer = window.setTimeout("check_shouts()", sb_interval);
}

function shout_out(){

	// Check already submiting shout
	if(sb_shouting === true) return;

	// Get value
	var shout_text = $("#sb_i").val().trim();
	if(shout_text == ""){
		$("#sb_i").select();
		$("#sb_i").focus();
		return;
	}

	// Stop auto-checker
	window.clearTimeout(sb_timer);
	sb_timer = null;

	// Ajax call
	sb_shouting = true;
	$("#sb_i").val('Please wait...');
	$.getJSON(make_link("Service", "Shout-Out"), { ShoutText: shout_text, LastShout: sb_last }, function(data){

		// Restore shout input box
		sb_shouting = false;
		$("#sb_i").val("");

		// Error
		if(data["error"] === true){

			// Resume auto-checker
			sb_timer = window.setTimeout("check_shouts()", sb_interval);

			alert("Could not post your shout:\n\n" + data["error_code"]);
			return;
		}

		// Check new achievement
		if(data["new_ach"] == true){
			redirect(make_link("Profile", "Achievements", {gojsback:1}));
			return;
		}

		// Update shouts
		update_shouts(data["shouts"], data["last_shout"]);
	});
}


$(document).ready(function(){

	// Check shoutbox object is loaded on this page
	if(!document.getElementById("sb_i")) return;

	// Start auto-checker
	check_shouts();

	$("#sb_i").keydown(function(e){
		if(e.keyCode == 13){
			shout_out();
		}
	});

	$("#sb_b").click(shout_out);
});

function bookmark_us(){

	var url = "http://mobizaar.com/?bookmark";
	var title = "Mobizaar.com - Free ringtones and wallpapers";

	// MSIE
	try{
		window.external.AddFavorite(url, title); return;
	}catch(e){; }

	// Firefox and Safari
	alert("Press <Control>+D to add Mobizaar to your bookmarks.\n\nThank you.");
}