// Populate states select #########################################################

function populate_states(form_id, select_name_country, select_name_states, select_name_cities, selected_state, select_mode){
		
	var countries_select = $("select[name='" + select_name_country + "']", "#" + form_id);	
	var states_select = $("select[name='" + select_name_states + "']", "#" + form_id);
	var cities_select = $("select[name='" + select_name_cities + "']", "#" + form_id);	
	
	states_select.empty().attr("disabled", "disabled").append("<option value=\"0\">" + txt_loading + "</option>");
	cities_select.empty().attr("disabled", "disabled").append("<option value=\"0\">" + txt_loading + "</option>");
	
	var country_selection = null;
	
	// Solve IE6 select bug
	if ($.browser.msie && ($.browser.version < 7)) {
		var opts = countries_select.find("option:selected");
		
		if (opts.length > 1) {
			country_selection = $(opts[opts.length - 1]).attr("value");
		}
	}
	
	if (country_selection == null) {
		country_selection = countries_select.val();
	}
	
	selected_state = parseInt(selected_state);
		
		if ((select_mode != undefined) && (select_mode != "") && (select_mode != 0)) {
			var URL = do_link("site.remote", "request=states&fk_countries=" + country_selection + "&select_mode=" + select_mode);
		}
		else {
			var URL = do_link("site.remote", "request=states&fk_countries=" + country_selection);
		}
		states_select.load(URL, {}, function(){
			
			states_select.removeAttr("disabled");
			
			if (selected_state > 0) {
				try {
					$(states_select.find("option").removeAttr("selected").filter("[value='" + selected_state + "']").get(0)).attr("selected", "selected");
				}
				catch(error){}
			}
			
			states_select.unbind("change").change(function(e){
				if (typeof(eval("return_states_" + form_id)) == "function") {
					eval("return_states_" + form_id + "();");
				}
			}).change();
			
		});
	

}

// ################################################################################

// Populate cities select #######################################################

function populate_cities(form_id, select_name_states, select_name_cities, selected_city, select_mode){
	
	var cities_select = $("select[name='" + select_name_cities + "']", "#" + form_id);
	var select_id_cities = $(cities_select).attr('id');
	
	var state_select = $("select[name='" + select_name_states + "']", "#" + form_id);
	
	var state_select_id = $(state_select).attr('id');
	var states_selection = $("'#" + state_select_id + " option:selected'", "#" + form_id).val();	
	
	cities_select.empty().attr("disabled", "disabled").append("<option value=\"0\">" + txt_loading + "</option>");
	
	// Solve IE6 select bug
	if ($.browser.msie && ($.browser.version < 7)) {
		var opts = state_select.find("option:selected");
		
		if (opts.length > 1) {
			states_selection = $(opts[opts.length - 1]).attr("value");
		}
	}
	
	if (states_selection == null) {
		states_selection = state_select.val();
	}
	
	states_selection = parseInt(states_selection);
	
	selected_city = parseInt(selected_city);
	
	if ((select_mode != undefined) && (select_mode != "") && (select_mode != 0)) {
		var URL = do_link("site.remote", "request=cities&fk_states=" + states_selection + "&select_mode=" + select_mode);
	}
	else {
		var URL = do_link("site.remote", "request=cities&fk_states=" + states_selection);
	}

	cities_select.load(URL, {}, function(){
		
		cities_select.removeAttr("disabled");
		
		if (selected_city > 0) {
			try {
				$(cities_select.find("option").removeAttr("selected").filter("[value='" + selected_city + "']").get(0)).attr("selected", "selected");
			}
			catch(error){}
		}
		
		if (typeof(callback) == "function") {
			callback.call();
		}
	});	
}

// ################################################################################

// Form functions #######################################################

// Focus on input
function form_focus(form_id){
	$("form#" + form_id + " :input[value='']:not(select):enabled:visible:first").focus();
}

// Disable submit button
function jform_do_submit(form_id, button_name){
	
	var my_form = $("form#" + form_id);
	
	my_form.submit(function() {
		if (!form_is_submitted) {
			$("form#" + form_id + " :button[name='" + button_name + "'],:submit[name='" + button_name + "']").attr("disabled", "disabled");
			
			form_is_submitted = 1;
			submitted_form = form_id;
			submission_button = button_name;
		}
	});
}

function toggle_change_countries(form_id, selected_country) {
	
	var zip_obj = jQuery("#zip_row", "#" + form_id);
	var state_city_obj = jQuery("#state_city_row", "#" + form_id);
	
	if ((selected_country != 'US') && (selected_country != 'CA')) {
		state_city_obj.show();
		zip_obj.hide();
		populate_states(form_id, "fk_countries", "fk_states", "fk_cities");
	}
	else {
		zip_obj.show();
		state_city_obj.hide();
	}
}

function toggle_change_countries_property(form_id, selected_country) {
	
	var state_city_obj = jQuery("#state_city_row", "#" + form_id);
	
	if ((selected_country != 'US') && (selected_country != 'CA')) {
		state_city_obj.show();		
		populate_states(form_id, "fk_countries", "fk_states", "fk_cities");
	}
	else {		
		state_city_obj.hide();
	}
}

function toggle_location_panels(form_id, location, state){
	
	if (location == "choose") {
		$("#panel_predefined").show();
		$("#panel_define").hide();
		
		$("form#" + form_id + " :hidden[name='location']").attr({value: "choose"});
	}
	else if (location == "define") {

		populate_states("site_register", "fk_countries", "fk_states", "fk_cities", state);
		
		$("#panel_predefined").hide();
		$("#panel_define").show();
		
		$("form#" + form_id + " :hidden[name='location']").attr({value: "define"});
	}
	
}

function toggle_countries_change(form_id,country_selected){
	
	if (country_selected == "US" || country_selected == "CA") {
		$("#zip_row").show();
		$("#states_row").hide();
		$("#cities_row").hide();
		
	}
	else {
		populate_states("site_register", "fk_countries", "fk_states", "fk_cities", '');
		
		$("#zip_row").hide();
		$("#states_row").show();
		$("#cities_row").show();
	}
	
}

function jform_set_select(sel_name, form_id, sel_value){
	$("form#" + form_id + " select[name='" + sel_name + "']:first").selectOptions(sel_value, true);
}

function jform_set_radio(radio_name, form_id, selected_value){
	// $("form#" + form_id + " :radio[name='" + radio_name + "'][value='" + selected_value + "']:first").attr("checked", "checked");
	
	var this_radio = jQuery("form#" + form_id + " :radio[name='" + radio_name + "'][value='" + selected_value + "']:first");
	
	if (jQuery(this_radio).length > 0) {
		jQuery(this_radio).click();
	}
}

function jform_set_checked(check_name, form_id, checked_mode){
	if (checked_mode != "" && checked_mode != 0 && checked_mode != "off") {
		$("form#" + form_id + " :checkbox[name='" + check_name + "']:first").attr("checked", "checked");
	}
}

function jform_check_all(form_id){
	$("form#" + form_id + " :checkbox").attr("checked", "checked");
}

function jform_uncheck_all(form_id){
	$("form#" + form_id + " :checkbox").removeAttr("checked");
}

// ################################################################################

function was_rated(jokes_key, jokes_rate, returned_average){

	dom_toggle_element("ratemenu" + jokes_key, false);
	dom_toggle_element("hide_rate" + jokes_key, true);

	jokes_rating_pic = document.getElementById("jokes_rating_pic" + jokes_key);

	jokes_rating_pic.src = PATH + "/img/site/rating/bar_" + Math.ceil(returned_average) + ".gif";
}

function form_set_select_id(sel_id, form_name, sel_index) {
	var obj = dom_get_element(sel_id);

	var sel_length = obj.length;

	for (optionCounter = 0; optionCounter < sel_length; optionCounter++) {
		if (obj.options[optionCounter].value == sel_index){
			obj.selectedIndex = optionCounter;
		}
	}
}

function CounterText(field, cntfield, maxlimit) {
	var obj_field = dom_get_element(field);
	var obj_cntfield = dom_get_element(cntfield);
	if (obj_field.value.length > maxlimit){
        		obj_field.value = obj_field.value.substring(0, maxlimit);
	}
   	else {
       		obj_cntfield.value = maxlimit - obj_field.value.length;
   	}
}


function set_smiley(text_area, add_smiley){ 
      
	eval(text_area + ".value = " + text_area + ".value + ' " + add_smiley + " ';");
	eval(text_area + ".focus();");
	
}

// Cookies #######################################################

function getCookieVal (offset) {
	
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
	
	var arg = name+"=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	
	while (i < clen) {
		var j = i+alen;
		if (document.cookie.substring(i, j) == arg) {
			return getCookieVal (j);
		}		
		i=document.cookie.indexOf(" ", i)+1;
		if (i==0) break;
	}
	return null;
}

function FixCookieDate (date) {
	
	var base = new Date(0);
	var skew = base.getTime(); // dawn of (Unix) time - should be 0
	if (skew > 0) { // Except on the Mac - ahead of its time
		date.setTime (date.getTime() - skew);
	}
}

function SetCookie (name,value,expires,path,domain,secure) {
	
	document.cookie = name + "=" + escape (value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function DelCookie(name) { // use: deleteCookie("name");
	
	var today = new Date();
	var expired = new Date(today.getTime() - 28 * 24 * 60 * 60 * 1000); // less 28 days
	document.cookie = name + "=null; expires=" + expired.toGMTString() + "; path=/"; // delete cookie
	//bikky = document.cookie; // update bikky
}

function DeleteCookie (name,path,domain) {
	if (GetCookie(name)) {
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// ################################################################################

function toggle_nav_bar(){
	
	var cookie_pfk = get_cookie('pfk');
	var cookie_username = get_cookie('_USR[logins_username]');
	var tab_welcome = dom_get_element("tab_welcome");
			
	if (cookie_pfk > 0) {
		tab_welcome.innerHTML = "Bine ai venit, <a href='" + do_link("user.editeaza_profil", "") + "' class='link_text_menu'>" + cookie_username + "</a>!&nbsp;&nbsp;&nbsp;";
		dom_toggle_element("tab_logout_left", true);
		dom_toggle_element("tab_logout", true);
		dom_toggle_element("tab_account_left", true);
		dom_toggle_element("tab_account", true);
	}
	else {
		tab_welcome.innerHTML = "";
		dom_toggle_element("tab_register_left", true);
		dom_toggle_element("tab_register", true);
		dom_toggle_element("tab_login_left", true);
		dom_toggle_element("tab_login", true);
		
		if (cookie_username == null) {
			dom_toggle_element("tab_registration_banner", true);
		}
	}			
}

function pic_edit(files_key) {

	if (editor_is_open == 0) {
		myBox = new Boxy("<iframe src=\"" + do_link("site.cropper", "files_key=" + files_key) + "?" + Math.floor(Math.random() * 10000000000) + "\"  framespacing=\"0\" frameborder=\"no\" scrolling=\"no\" width=\"900\" height=\"600\"></iframe>", {
			title: "Edit",
			closeText: "[" + link_close + "]",
			closeable: true,
			draggable: true
		});
	}
	
	editor_is_open = 1;
}

function on_pic_edit_close() {
	
	editor_is_open = 0;
	
	var big_path = jQuery("#big_pic").attr("src");
	var left_path = jQuery("#left_pic").attr("src");
	var top_path = jQuery("#top_pic").attr("src");
	
	if (big_path) {
		jQuery("#big_pic").attr("src", big_path.substr(0, big_path.indexOf("?") + 1) + Math.floor(Math.random() * 10000000000));
	}
	
	if (left_path) {
		jQuery("#left_pic").attr("src", left_path.substr(0, left_path.indexOf("?") + 1) + Math.floor(Math.random() * 10000000000));
	}
	
	if (top_path) {
		jQuery("#top_pic").attr("src", top_path.substr(0, top_path.indexOf("?") + 1) + Math.floor(Math.random() * 10000000000));
	}
	
	jQuery.each(jQuery("a.a_change img"), function(i, v) {
		var path = jQuery(v).attr("src");
		
		jQuery(v).attr("src", path.substr(0, path.indexOf("?") + 1) + Math.floor(Math.random() * 10000000000));
	});
}

function show_cropper(options){
	
	myBox = new Boxy("<iframe name=\"cropper\" src=\"" + options.link + "&rv=" + Math.floor(Math.random() * 10000000000)  + "\"  framespacing=\"0\" frameborder=\"no\" scrolling=\"no\" width=\"" + options.width + "\" height=\"" + options.height + "\"></iframe>", {
		title: txt_edit,
		closeText: "<span class='close_box'>[ <a href='#' class='close'>" + "close" + "</a> ] <a href='#' class='close'><img src='" + PATH + "/img/site/btn_close.gif' align='absmiddle'></a></span>",
		closeable: true,
		modal: true,
		unload: true,
		animate: 0,
		afterHide: function(){
			jQuery("img[src*=" + options.key + "]").each(function(i, v){
				var jThis = jQuery(this);
				
				var d = new Date;
				if (typeof(jThis.attr("src")) != "undefined") {
					var full_path = jThis.attr("src");
					var img_path = full_path.substr(0, (full_path.length - 4));
					
					var tmp = img_path.split(".v");
					if (tmp.length > 1) {
						delete tmp[tmp.length -1];
						img_path = tmp.join("");
					}
					
					var img_ext = full_path.substr(full_path.length - 4);
				}
				
				jThis.attr("src", img_path + ".v" + d.getTime() + img_ext);
				
				if (typeof(jThis.metadata().path_medium) != "undefined") {
					
					var full_path = jThis.metadata().path_medium;
					var img_path = full_path.substr(0, (full_path.length - 4));
					
					var tmp = img_path.split(".v");
					if (tmp.length > 1) {
						delete tmp[tmp.length -1];
						img_path = tmp.join("");
					}
					
					var img_ext = full_path.substr(full_path.length - 4);
					
					jThis.metadata().path_medium = img_path + ".v" + d.getTime() + img_ext;
				}
			});
		}
	});
}

/*function start_cropper(_minWidth, _minHeight, _aspectRatio, _x1, _y1, _x2, _y2) {
	
	
	if ($("#big_pic").height() < _y2) {
		_y1 = _y1 - (_y2 - $("#big_pic").height());
		_y2 = $("#big_pic").height();
	}
	
	if ($("#big_pic").width() < _x2) {
		_x1 = _x1 - (_x2 - $("#big_pic").width());
		_x2 = $("#big_pic").width();
	}
	
	$("#big_pic").imgAreaSelect({
		parent: "#wrap",
		single: true,
		onSelectEnd: selectEnd,
		onSelectChange: selectChange,
		minWidth: _minWidth,
		minHeight: _minHeight,
		aspectRatio: _aspectRatio,
		selectionColor: "#fff",
		selectionOpacity: 0.2,
		outerColor: "#000",
		outerOpacity: 0.2,
		borderWidth: 1,
		x1: _x1,
		y1: _y1,
		x2: _x2,
		y2: _y2
	});
}*/

function invite_box() {
	
	var variable = "inv_signup";
	var inv_cookie = GetCookie(variable);
	var was_logged = GetCookie("_USR[logins_username]");

	if ((inv_cookie != 1) && (was_logged == null)) {
		
		myBox = new Boxy('<div style=\"width: 460px; height: 330px;\"><div class="clearfix"><img src="/img/logo/shopmania-logo.gif" style="margin-top: 0.5em; margin-left: 1em;" /><img src="/img/logo/shopmania.gif" align="top" style="margin-top: 0.5em;" /></div> <hr /><div class="pad_1">' + txt_signup +'<br /> </div> <div class="center"><a href="' + link_signup + '" style=\"display: block; margin: 0 auto; color: #FFFFFF; text-decoration: none; font-weight: bold; font-size: 108%; width: 230px; height: 38px; background: url(\'/img/site/btn_signup.gif\') no-repeat top left; text-align: center; line-height: 38px;\">' + btn_signup + '</a></div><br /> <hr /> <div><h2 class="center dark">' + btn_signup + '</h2></div></div>', {
			title: btn_signup,
			closeText: "[" + link_close + "]",
			closeable: true,
			draggable: true,
			modal: true
		});
	        
		var expdate = new Date();
		FixCookieDate (expdate);
		expdate.setTime(expdate.getTime() + 5*24*60*60*1000);
		
		SetCookie (variable, 1, expdate, "/" , DOMAIN_BASE);
	}
	
}

// Alternate rows #######################################################

function color_on(obj){
	obj.style.backgroundColor = "#FEFFDB";
}

function color_off(obj){
	obj.style.backgroundColor = "transparent";
}

function opt_row_on(key){
	dom_get_element("row_" + key).style.visibility = 'visible';
}

function opt_row_off(key){
	// setTimeout("dom_get_element('row_' + " + key + ").style.visibility = 'hidden';", 500);
	dom_get_element("row_" + key).style.visibility = 'hidden';
}

// ################################################################################

// Tabs functions #######################################################

function box_show(mode){
	
	jQuery.each(tabs, function(i, v) {
		jQuery("#b_" + v).hide();
		jQuery("#m_" + v).removeClass("on");
	});
	
	jQuery("#b_" + mode).show();
	
	jQuery("#m_" + mode).addClass("on");
	
	
}

function auto_box(){
	var str = document.location.toString();
	var nr = str.indexOf("#") + 1;
	var cmd;

	if (nr > 0) {
		cmd = str.substr(nr);
	}
	else {
		cmd = "";
	}
	
	for (var i=0; i<tabs.length; i++) {
		
		if (cmd == tabs[i] && (dom_get_element("m_" + tabs[i]).style.display != "none")) {
			box_show(cmd);
			break;
		}
	}
}

function toggle_left_section(mode){
	
	dom_toggle_element(mode + "_menu");
	
	if (dom_get_element(mode + "_menu").style.display == "none") {
		//dom_get_element(mode + "_img").className = "img_plus";
	}
	else {
		//dom_get_element(mode + "_img").className = "img_minus";
	}
}

// ################################################################################

// User interaction #######################################################

function getSelectedRadio(buttonGroup) {
	if (buttonGroup[0]) {
		for (var i=0; i<buttonGroup.length; i++) {
			if (buttonGroup[i].checked) {
				return i
			}
		}
	} else {
		if (buttonGroup.checked) { return 0; }
	}
	
	return -1;
}

function getSelectedRadioValue(buttonGroup) {
	var i = getSelectedRadio(buttonGroup);
	
	if (i == -1) {
		return "";
	} else {
		if (buttonGroup[i]) {
			return buttonGroup[i].value;
		} else {
			return buttonGroup.value;
		}
	}
}

function block_handling(how){
	var block = dom_get_element("can_block");
	var unblock = dom_get_element("can_unblock");
			
	if (how == "can_unblock") {
		block.style.display = "none";
		unblock.style.display = "";
		
	}
	else {		
		unblock.style.display = "none";
		block.style.display = "";
	}
}

function action_handling(how){
	var buddy = dom_get_element("can_buddy");
	var unbuddy = dom_get_element("can_unbuddy");
			
	if (how == "can_unbuddy") {
		buddy.style.display = "none";
		unbuddy.style.display = "";
		
	}
	else {		
		unbuddy.style.display = "none";
		buddy.style.display = "";
		
	}
}

function friend_handling(how){
	
	var all_actions = jQuery(".friend_action");
		
	if (how == "direct") {
		all_actions.hide();
		jQuery("#friend_direct").show();
	}
	else if (how == "opposite") {
		all_actions.hide();
		jQuery("#friend_opposite").show();
	}
	else if (how == "mutual") {
		all_actions.hide();
		jQuery("#friend_mutual").show();
	}
	else {
		all_actions.hide();
		jQuery("#friend_not_yet").show();
	}
}

function show_quest(mode){
	
	jQuery("div[id^='Q_']").hide();
	
	jQuery("#Q_" + mode).show();
	
}



// ################################################################################

// User actions #######################################################

function return_location_fav(key, msg){
	
	$("msg_" + key).innerHTML = "<span class=\"hint\">" + msg + "</span>";
	
	new Effect.Highlight("msg_" + key, { startcolor: '#FFFF44', endcolor: '#E9FEE9' });
}

function return_event_fav(key, msg){
	
	$("msg_" + key).innerHTML = "<span class=\"hint\">" + msg + "</span>";
	
	new Effect.Highlight("msg_" + key, { startcolor: '#FFFF44', endcolor: '#E9FEE9' });
}

function return_prod_fav_del(key, msg){
	
	$("msg").innerHTML = "<span class=\"hint\">" + msg + "</span>";
	
	new Effect.Highlight("msg", { startcolor: '#FFFF44', endcolor: '#E9FEE9' });
}

function return_help_track(key, msg){
	
	$("msg").innerHTML = "<span class=\"hint\">" + msg + "</span>";
	
	new Effect.Highlight("msg", { startcolor: '#FFFF44', endcolor: '#E9FEE9' });
}

function return_profile_action(key, msg, _title){
	Boxy.alert("<b>" + msg + "</b><br /><br />", null, {title: _title, fixed: false});
}

function return_location_comm_rating(key, msg, value){
	
	if (msg == "Votul a fost inregistrat cu succes.") {
		
		var val = parseInt($("rating_" + key).innerHTML) + parseInt(value);
		
		if (val == 0) {
			show_comm(key);
			$("rating_" + key).className = "bold mark_pending";
		}
		if (val < 0) {
			hide_comm(key);
			$("rating_" + key).className = "bold mark_inactive";
		}
		if (val > 0) {
			$("rating_" + key).className = "bold mark_active";
		}
		
		$("rating_" + key).innerHTML = val;
	}
	
	$("rmsg_" + key).innerHTML = "<span class=\"hint\">" + msg + "</span>";
	
	new Effect.Highlight("rmsg_" + key, { startcolor: '#FFFF44'});
}

function init_request(id){
	dom_get_element(id).innerHTML = "<img src=\"/img/site/loading.gif\">";
}

function hide_comm(key) {
	dom_toggle_element("com_" + key, false);
	dom_toggle_element("reply_" + key, false);
	dom_toggle_element("show_" + key, true);
	dom_toggle_element("hide_" + key, false);
}

function show_comm(key) {
	dom_toggle_element("com_" + key, true);
	dom_toggle_element("reply_" + key, true);
	dom_toggle_element("show_" + key, false);
	dom_toggle_element("hide_" + key, false);
}

function item_action(item_action, item_key, item_note){
	
	if (item_action == "buddy" || item_action == "edit_note") {	
		var URL = do_link("site.remote", "request=" + item_action + "&item_key=" + item_key + "&item_note=" + item_note);	
	}
	else {
		var URL = do_link("site.remote", "request=" + item_action + "&item_key=" + item_key);
	}
	
	remote_data_request(URL, "_RETURN=" + RETURN, "");
}

function edit_note(item_key, item_note){
	
	var url = do_link("site.remote", "request=edit_note");
	
	$.ajax({
		type: "POST",
		url: url,
		data: "item_key=" + item_key + "&item_note=" + item_note,
		success: function(msg){
			jQuery('#rel_note_'+item_key).text(item_note);
			Boxy.alert("<b>" + msg + "</b><br /><br />", function(){
				location.reload(true);
			},
			{title: "Add / Edit Note"});
		}
	});	
}

function view_gallery(link, my_title){
	
	if (editor_is_open == 0) {
		myBox = new Boxy("<iframe src=\"" + link + "?" + Math.floor(Math.random() * 10000000000) + "\"  framespacing=\"0\" frameborder=\"no\" scrolling=\"no\" width=\"750\" height=\"600\"></iframe>", {
			title: my_title,
			closeText: "[" + link_close + "]",
			closeable: true,
			draggable: true
		});
	}
	
	editor_is_open = 1;
}

function view_iframe(link, my_title, width, height, ele){
	
	ele = jQuery(ele);
	
	myBox = new Boxy("<iframe src=\"" + link + "&" + Math.floor(Math.random() * 10000000000) + "\"  framespacing=\"0\" frameborder=\"no\" scrolling=\"no\" width=\"" + width + "\" height=\"" + height + "\"></iframe>", {
		title: my_title,
		closeText: "[" + link_close + "]",
		closeable: true,
		draggable: true,
		fixed: false
	});
	
	return myBox;
}


function update_new_msg(nr){
	
	if (nr > 0) {
		$("#mailbox").text("My Email (" + nr + ")");
		
		// Check if link is not pulsing
		if ($("#mailbox").hasClass("recover")) {
			$("#mailbox").pulse({
				textColors: ['#be1600','#fff'],
				speed: 500
			})
			.removeClass("recover")
			.addClass("pulse");
		}
	}
	else {
		// Stop the pulsing
		$("#mailbox").text("My Email ").recover().removeClass("pulse").addClass("recover");
	}
}

function check_buddy_online() {
	
	var URL = do_link("site.remote", "request=check_buddy_online");
	
	$.getScript(URL, function(){
		if (count_buddy_online > 0) {
			jQuery("#cnt_buddy_online").text("(" + count_buddy_online + ")").css("color", "#be1600");
		}
		else {
			jQuery("#cnt_buddy_online").text("");
		}
				
		setTimeout("check_buddy_online();", 15000);
	});
}

function check_new_messages() {
	
	var URL = do_link("site.remote", "request=check_new_messages");
	
	$.getScript(URL, function(){
		update_new_msg(count_new_messages);	
		setTimeout("check_new_messages();", 15000);
	});	
}

// Link dom from the tab header
function jBoxShow(tab) {
	
	var ul = jQuery(tab).parents().get(2);
	var li = jQuery(tab).parents().get(1);
	var li = jQuery(li);
	
	if (li.is(":visible") === true) {
		jQuery(ul).find("li").each(function(i, v) {
			
			v = jQuery(v);
			v.removeClass("on");
			jQuery("#" + v.attr("rel")).hide();
			jQuery("#t" + v.attr("rel")).hide();
		
		});
		
		li.addClass("on");
		jQuery("#" + li.attr("rel")).show();
		jQuery("#t" + li.attr("rel")).show();
		location.hash = li.attr("rel").substr(2);
	}
}

// Header menu ID
function jAutoBox(menu) {
	
	var link = jQuery("#" + menu + " li#m_" + location.hash.substr(1) + ":visible a");
	
	// alert(link.length);
	
	if (link.length > 0) {
		jBoxShow(link);
	}
	// Get first visible link
	else {
		var new_link = jQuery("#" + menu + " li:visible:first a");
		
		// We have a link
		if (new_link.length > 0) {
			jBoxShow(new_link);
		}
	}
	
	// Bind events
	jQuery("#" + menu + " li a").click(function(e){
		jBoxShow(this);
		e.preventDefault(); e.stopPropagation();
	});
}

function jActiveRow(row) {
	
	// Bind events
	jQuery("." + row).mouseover(function(e){
		jQuery(this).attr("bg", jQuery(this).css("background-color"));
		jQuery(this).css({backgroundColor: "#FEFFDB"});
	});
	
	jQuery("." + row).mouseout(function(e){
		jQuery(this).css({backgroundColor: jQuery(this).attr("bg")});
	});
}

// Disable right click #######################################################

function clickIE4(){
	
	if (event.button == 2) {
		return false;
	}
}

function clickNS4(e){
	
	if (document.layers || document.getElementById && !document.all) {
		
		if ( (e.which == 2) || (e.which == 3) ) {
			return false;
		}
	}
}

function disable_right_click() {
	
	if (document.layers) {
		document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown = clickNS4;
	}
	else if (document.all && !document.getElementById) {
		document.onmousedown = clickIE4;
	}
	
	document.oncontextmenu = new Function("return false");
}

// ################################################################################

function submit_search_form(form_name, button_name){
	
	var arr = button_name.split(",");
	
	if (!form_is_submitted) {
		
		for (var i=0; i<arr.length; i++) {
			eval("document." + form_name + "." + arr[i].replace(/\s/g,"") + ".disabled=true");
		}
		
		eval("document." + form_name + ".submit()");
		eval("submitted_form = '" + form_name + "'");
		eval("submission_button = '" + button_name + "'");
		form_is_submitted = 1;
	}
	
	return false;
}

function set_progress_bar(percent) {
	jQuery(".progress em").css({width: percent + '%'});
}

function window_open(url, name, type) {
	
	var win = null;
	var win_scroll = 'yes';
	var win_resizable = 'yes';
	var win_toolbar = '';
	var win_location = '';
	var win_status = '';
	var win_menubar = '';
	
	if (type == "profile") {
		var w = 750;
		var h = 600;
		var LeftPosition = 25;
		var TopPosition = 25;
	}
	else if(type == "mailbox") {
		var w = 800;
		var h = 600;
		var TopPosition = (screen.width - 650) / 2;
		var LeftPosition = (screen.height - 500) / 2;
	}
	else if(type == "gallery") {
		var w = 800;
		var h = 680;
		var TopPosition = (screen.width - 650) / 2 - 200;
		var LeftPosition = (screen.height - 500) / 2;
	}
	else if(type == "property") {
		var w = 600;
		var h = 600;
		var TopPosition = (screen.width - 650) / 2 - 150;
		var LeftPosition = (screen.height - 500) / 2 + 200;
	}
	else if(type == "travel") {
		var w = 800;
		var h = 610;
		var TopPosition = (screen.width - 650) / 2 - 200;
		var LeftPosition = (screen.height - 500) / 2;
	}
	else {
		var w = 600;
		var h = 600;
		var LeftPosition = (screen.width) ? ((screen.width-w) / 2) : 0;
		var TopPosition = (screen.height) ? ((screen.height-h) / 2) : 0;
	}
	settings = 'height = ' + h + ', width = ' + w + ', top = ' + TopPosition + ', left = ' + LeftPosition;
	settings += (win_scroll == "yes") ? ", scrollbars=yes" : ", scrollbars=no";
	settings += (win_resizable == "yes") ? ", resizable=yes" : ", resizable=no";
	settings += (win_toolbar == "yes") ? ", toolbar=yes" : ", toolbar=no";
	settings += (win_location == "yes") ? ", location=yes" : ", location=no";
	settings += (win_status == "yes") ? ", status=yes" : ", status=no";
	settings += (win_menubar == "yes") ? ", menubar=yes" : ", menubar=no";
	
	win = window.open(url, name, settings);
	
	if (win == null) {
		alert("Your popup blocker stopped an window from opening\nPlease disable your popup blocker if you wish to see window content!");
	}
	
}

var myBox;
var myBoxOl;

function start_ol(page, params, my_title, width, height){
	
	params += "&rv=" + Math.floor(Math.random() * 10000000000);
	
	myBoxOl = new Boxy("<iframe name=\"overlay\" src=\"" + do_link(page, params)  + "\"  framespacing=\"0\" frameborder=\"no\" scrolling=\"no\" width=\"" + width + "\" height=\"" + height + "\"></iframe>", {
		title: my_title,
		closeText: "[" + link_close + "]",
		//closeText: "<span class='close_box'>[ <a href='#' class='close'>" + link_close + "</a> ] <a href='#' class='close'><img src='" + PATH_STATIC + "/img/site/btn_close.gif' align='absmiddle'></a></span>",
		closeable: true,
		modal: true
	});
}

function travel_delete(key, type){
	
	// Confirm the deletion
	Boxy.confirm("Are you sure you want to delete this " + type + "?", function() {
		jQuery.ajax({
			type: "POST",
			url: do_link("site.remote", "request=delete_travel"),				
			data: "travel_key=" + key + "&travel_type=" + type,
			dataType: "json",
			
			// On success, display a message and remove the travel item from the DOM
			success: function(data){
				Boxy.alert(data.msg, function(){
					if(data.success == "yes") {
						jQuery('.travel_'+key).fadeOut(1000, function(){jQuery(this).remove()});
					}	
				},
				{title: 'Delete ' + type});										
			}
		});
	},
	{title: 'Delete itinerary'});
}

function randomString() {
	var chars = "123456789abcdefghiklmnpqrstuvwxyz";
	var string_length = 11;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

// Randomly change the travel-photos banner
function change_random_travel_photo(){
	// Get current pics
	var pics = "";
	jQuery('ul li', '#top_banner').each(function(){
		//console.log(jQuery(this).attr('id'));
		pics += jQuery(this).attr('id').split('_')[1] + "|";
	});
	
	// Get a random photo
	jQuery.ajax({
		type: "POST",
		url: do_link("site.remote", "request=get_random_travel_photo"),
		data: "pics="+pics,
		success: function(data){
			var file_path = data.split('|')[0];
			var travel_key = data.split('|')[1];
			var file_key = data.split('|')[2];
						
			// Get a random number from 0 to 7
			var rand = Math.floor(Math.random()*8);
			
			var link_travel = do_link("site.album", "travel_key="+travel_key+"&pp=up");

			html_block = "<a onclick=\"window_open('" + link_travel + "', 'Album_"+travel_key+"', 'travel');return false;\" href=\"http://www.swfam.asesoftnet.com/album?travel_key="+travel_key+"&amp;pp=up\"><img alt=\"travel pic\" src=\""+file_path+"\"/></a>";
			jQuery("ul li:eq("+rand+")", "#top_banner").fadeOut('slow', function(){jQuery(this).html(html_block).fadeIn('slow')}).attr('id', 'pic_' + file_key);
		}
	});
		
	setTimeout('change_random_travel_photo();', 5000);
}

// Check promo code and return a total price
function check_promo_code(){
	var valid = "<img align='absmiddle' src='" + PATH + "/img/site/valid.png' alt='Valid code' />";
	var invalid = "<img align='absmiddle' src='" + PATH + "/img/site/invalid.png' alt='Invalid code' />";
	var none = "";
	
	// Show loader
	jQuery('#code_valid').html("");
	jQuery('#loader').show();
	
	// Check promo code remoteley
	var url = do_link("site.remote", "request=check_promo_code");
	var code = jQuery('#fk_promo_codes').val();
	jQuery.ajax({
		type: "POST",
		url: url,
		data: "code=" + code + "&fk_mbs=" + jQuery('input:radio:checked').val(),
		dataType: "json",
		success: function(code){
			// Hide loader
			jQuery('#loader').hide();
			if(code.valid == "true") {
				jQuery('#code_valid').html(valid);
			}
			else if (code.valid == "none") {
				jQuery('#code_valid').html(none);
			}
			else {
				jQuery('#code_valid').html(invalid);
			}
			
			jQuery('#total_cost').text(code.price);
		}
	});
}

// Fix broken button for upload
jQuery(function(){
	jQuery('span', '#btnCancel').wrapInner('<em></em>');
});

