var ajax_loading = '<span class="loading"><img src="/images/common/loading.gif" style="border:none;" /> loading...</span>';
var ajax_saving = '<span class="loading"><img src="/images/common/loading.gif" style="border:none;" /> saving...</span>';

$(document).ready(function() {
	$('#sitesearchbar').textdropdown();

	$("#show_login_btn").css("cursor", "pointer").click(function() {
		$("#header_login_box").hide();
		$("#header_login_form").show();
	});

        $("#headher_login_btn").click(function() {

		if(!$("#header_username").val() || !$("#header_password").val())
		{
			return false;
		} else
		{
			return true;
		}
        });

	$("[@id^='add_friend_btn_']").css("cursor", "pointer").click(function() {
		var member_id = $(this).attr("id").replace("add_friend_btn_", "");
		add_friend(member_id);
	});

        $("[@id^='add_star_btn_']").css("cursor", "pointer").click(function() {
                var member_id = $(this).attr("id").replace("add_star_btn_", "");
		add_star(member_id);
        });

        $(".listings-thread TR:nth-child(odd)").addClass("alt-row");
        $(".listings-thread TR:nth-child(odd) .tr-inner").css("background-color", "#FFFFFF");
        $(".listings-thread TR:nth-child(1) TD").addClass("b-top");
        $(".listings-inner TR:nth-child(1) TD").addClass("b-top");

	// fix firefox ellipsis display
	if ($.browser.mozilla) {
		$(".ellipsis").each(function(){
			if ($(this).children("span").width() > $(this).width()) {
				$(this).children("span").css("display", "block");
				$(this).children("span").css("float", "left");
				$(this).children("span").css("white-space", "nowrap");
				$(this).children("span").css("overflow", "hidden");
				$(this).children("span").width($(this).width()-15);
				$(this).children("span").after("<span style='float:right;'>...</span>");
			}
		});	
	}

	// 2-line caption ellipsis effect
	/*$(".caption_96, .caption_64").each(function(){
		var len, substr;

		if ($(this).children("span").height() > $(this).height()) {
			len = 1.6 * $(this).children("span").text().length / ($(this).children("span").height() / $(this).height() * 2);
			substr = $(this).children("span").text().substr(0, Math.floor(len));
			$(this).children("span").text(substr + " ...")
		}
	});*/
	
	$(".caption_120, .caption_96, .caption_64").each(function(){
		var len; 
	
		if ($("span", this).height() > $(this).height()) {
			len = 1.6 * $("span", this).text().length / ($("span", this).height() / $(this).height() * 2);
			substr = $("span", this).text().substr(0, Math.floor(len));
			$("span", this).text(substr + " ..."); 
		}
	});	

	$("img[@src$=png]").pngfix();
	$("DIV[class^=pointer_]").pngfix();
	$("DIV[class^=pointer-]").pngfix();
	$("TD[class^=tab_discover_]").pngfix();
	$("TD[class^=tab_connect_]").pngfix();
	$("TD[class^=tab_buy_]").pngfix();

	$("#404_search_box").focus(function () {
		if ($(this).val() == "search") {
			$(this).val("");
			$(this).css("color", "black");
		}
	});

	
        $("#r_password").keydown(function(e) {
                if(e.keyCode==13)
                {
			reset_password();
                }
        });
        $("#r_confirm_password").keydown(function(e) {
                if(e.keyCode==13)
                {
			reset_password();
                }
        });
	$("#reset_password_btn").click(function() {
		reset_password();
	});

/*
	$("#dob_day,#dob_month,#dob_year").change(function() {
		verify_dob();
	});
*/

        $("#dob_day,#dob_month,#dob_year").change(function() {
                $("#dob_error").html('');
        });
});

jQuery.fn.textdropdown = function() {
	with ($(this)) {
/*
		with (find(".sb_qry")) {
			if (val() == "") {
				val(attr("default"));
				css("color", "#9E9E9E");
			}
		}
*/

		with (find('li')) {
			click(function() {
				with ($(this).parents(".f_search_bar")) {
					var val = jQuery.trim($(this).html().replace(/&nbsp;/, ''));
					find('.sb_txt').html(val);
					find('input:first').attr("value", val);
				}
				$(this).parent().hide();
			});
		}

		find('.sb_btn, .sb_lst').click(function() {
			var p = $(this).parents(".f_search_bar");
			with (p.find('ul')) {
				css('position', 'absolute');
				css('top', p.position().top + 20)
				toggle();
			}
		});

/*
		find(".sb_qry").focus(function() {
			if ($(this).val() == $(this).attr("default") && $(this).css("color") != "black") {
				$(this).val("");
			}
			if ($(this).css("color") != "black") {
				$(this).css("color", "black");
			}
		});
*/

		find(".f_button").click(function() {
			var v = $(this).parents(".f_search_bar").find(".sb_qry");
			//if ((v.val() == v.attr("default") && v.css("color") != "black") || v.val() == "") {
			if (jQuery.trim(v.val()) == "") {
				return false;
			}
		});
	}
}

function reset_password()
{
	var password = $("#r_password").val();
	var confirm_password = $("#r_confirm_password").val();
	var error_msg =	"";
	if(password.length<1)
		error_msg = "please key	in the password.";
	else if(password.length<6)
		error_msg = "password must be at least 6 characters long.";
	else if(confirm_password.length<1)
		error_msg = "please confirm the	password.";
	else if(password!=confirm_password)
		error_msg = "confirm password doesn't match.";

	if(error_msg.length>0)
	{
		$("#reset_password_msg").html(error_msg);
		return false;
	} else
	{
		$("#reset_password_form").submit();
		return true;
	}
}

function urldecode( str	) 
{
	var histogram =	new Array()
	var histogram_r	= new Array();
	var 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.
   
	ret = replacer("%21", "!", ret);
	ret = replacer("%20", "+", ret);
 
	// End with decodeURIComponent,	which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);
 
	return ret;
}

function verify_dob()
{
        var dob_day = $("#dob_day").val();
        var dob_month = $("#dob_month").val();
        var dob_year = $("#dob_year").val();

        if(checkDate(dob_day+"-"+dob_month+"-"+dob_year))
        {
		$("#dob_error > em").addClass("input_success").html('&nbsp;');
                return true;
        } else
        {
                $("#dob_error").html('<em class="input_error">invalid date</em>');
                return false;
        }
}

function checkDate(dateStr) 
{
	var datePat = /^(\d{1,2})(\/|-)(.{3})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) return false;

	day = matchArray[1]; // p@rse date into variables
	year = matchArray[5];

	var month_name = new Array();

	month_name['Jan'] = '1';
	month_name['Feb'] = '2';
	month_name['Mar'] = '3';
	month_name['Apr'] = '4';
	month_name['May'] = '5';
	month_name['Jun'] = '6';
	month_name['Jul'] = '7';
	month_name['Aug'] = '8';
	month_name['Sep'] = '9';
	month_name['Oct'] = '10';
	month_name['Nov'] = '11';
	month_name['Dec'] = '12';

	month = month_name[matchArray[3]];

	if (month < 1 || month > 12) return false;
	if (day < 1 || day > 31) return false;
	if ((month==4 || month==6 || month==9 || month==11) && day==31) return false;

	if (month == 2) 
	{
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) return false;
	}
	return true; // date is valid
}

function show_login_dialog(callback_func)
{

	if($("#callback_func").length<1)
		$(document.body).append('<input type="hidden" name="callback_func" id="callback_func" value="'+callback_func+'" />');
	else
		$("#callback_func").val(callback_func);

	$.ajax({
		type: "POST",
		url: "/common/dialog/login/",
		data: {
			request_type: "load_dialog"
		},
		beforeSend: function(){
			show_dialog_loading();
		},
		success: function(xml){
			$(document.body).append("<div id='dim_overlay'></div>");
			$("#dim_overlay").show();
			$(document.body).append("<div id='dialog_box' style='display:none;'></div>");
			$("#dialog_box").html(xml).show();
		}
	});
}

function show_dialog_loading()
{
	var loading_html = "<div class='overlay_width'> <div class='box'><div class='tl'><div class='tr'><img src='/images/common/b.gif' /></div></div> <div class='box_con'>  <div class='global_padding overlay'><div style='text-align:center;padding:50px 0 50px 0;font-size:17px;color:#CC3300;'><img src='/images/common/loading_big.gif' /> loading...</div></div></div>   <div class='bl'><div class='br'><img src='/images/common/b.gif' /></div></div></div> </div>";

	if($("#dim_overlay").length<1)
	{
		$(document.body).append("<div id='dim_overlay'></div>");
		$("#dim_overlay").show();
	}
	if($("#dialog_box").length<1)
	{
		$(document.body).append("<div id='dialog_box' style='display:none;'></div>");
	}
	$("#dialog_box").html(loading_html).show();
}

function add_friend(member_id)
{
	if($("#add_friend_id").length>0)
		$("#add_friend_id").val(member_id);
	else
		$(document.body).append('<input type="hidden" id="add_friend_id" name="add_friend_id" value="'+member_id+'" />');

        if($("#member_logged_in").val()=="yes")
        {
                show_friend_dialog();
        } else
        {
                show_login_dialog("show_friend_dialog");
        }
}

function add_star(member_id)
{
	if($("#add_star_id").length>0)
		$("#add_star_id").val(member_id);
	else
		$(document.body).append('<input	type="hidden" id="add_star_id" name="add_star_id" value="'+member_id+'"	/>');

	if($("#member_logged_in").val()=="yes")
	{
		show_star_dialog();
	} else
	{
		show_login_dialog("show_star_dialog");
	}
}

function show_friend_dialog()
{
	var member_id = $("#add_friend_id").val();
	$.ajax({
		type: "POST",
		url: "/common/dialog/add-friend/",
		data: {
			member_id: member_id,
			request_type: "add_friend_dialog"
		},
		beforeSend: function(){
			show_dialog_loading();
		},
		success: function(xml){
                                $(document.body).append("<div id='dim_overlay'></div>");
                                $("#dim_overlay").show();
                        if($("#dialog_box").length<1)
                        {
                                $(document.body).append("<div id='dialog_box' style='display:none;'></div>");
                        }
                        $("#dialog_box").html(xml).show();
		}
	});
}

function show_star_dialog()
{
	var member_id =	$("#add_star_id").val();

	$.ajax({
		type: "POST",
		url: "/common/dialog/add-star/",
		data: {
			member_id: member_id,
			request_type: "add_star_dialog"
		},
		beforeSend: function(){
			show_dialog_loading();
		},
		success: function(xml){
				$(document.body).append("<div id='dim_overlay'></div>");
				$("#dim_overlay").show();
			if($("#dialog_box").length<1)
			{
				$(document.body).append("<div id='dialog_box' style='display:none;'></div>");
			}
			$("#dialog_box").html(xml).show();
		}
	});
}

function send_friend_gift(member_id)
{
        $.ajax({
                type: "POST",
                url: "/common/dialog/gift-member/",
                data: {
                        member_id: member_id,
                        request_type: "load_gift_member_dialog"
                },
                beforeSend: function(){
                        show_dialog_loading();
                },
                success: function(xml){
                                $(document.body).append("<div id='dim_overlay'></div>");
                                $("#dim_overlay").show();
                        if($("#dialog_box").length<1)
                        {
                                $(document.body).append("<div id='dialog_box' style='display:none;'></div>");
                        }
                        $("#dialog_box").html(xml).show();
                }
        });
}

function editor_insert_content(type)
{
        $.ajax({
                type: "POST",
                url: "/common/dialog/editor/",
                data: {
                        type: type,
                        request_type: "show_editor_dialog"
                },
                beforeSend: function(){
                        show_dialog_loading();
                },
                success: function(xml){
                        if($("#dim_overlay").length<1)
                        {
                                $(document.body).append("<div id='dim_overlay'></div>");
                                $("#dim_overlay").show();
                        }
                        if($("#dialog_box").length<1)
                        {
                                $(document.body).append("<div id='dialog_box' style='display:none;'></div>");
                        }
			$("#dialog_box").css("margin-left", "-200px");
                        $("#dialog_box").html(xml).show();
                }
        });
}

$.fn.insertAtCaret = function (myValue) {
        return this.each(function(){
                //IE support
                if (document.selection) {
                        this.focus();
                        sel = document.selection.createRange();
                        sel.text = myValue;
                        this.focus();
                }
                //MOZILLA/NETSCAPE support
                else if (this.selectionStart || this.selectionStart == '0') {
                        var startPos = this.selectionStart;
                        var endPos = this.selectionEnd;
                        var scrollTop = this.scrollTop;
                        this.value = this.value.substring(0, startPos)
                                      + myValue
                              	+ this.value.substring(endPos, this.value.length);
                        this.focus();
                        this.selectionStart = startPos + myValue.length;
                        this.selectionEnd = startPos + myValue.length;
                        this.scrollTop = scrollTop;
                } else {
                        this.value += myValue;
                        this.focus();
                }
        });

};

function show_download_license_dialog(download_id)
{
        $.ajax({
                type: "POST",
                url: "/common/dialog/download/",
                data: {
			download_id: download_id,
                        request_type: "show_download_license_dialog"
                },
                beforeSend: function(){
                        show_dialog_loading();
                },
                success: function(xml){
                        if($("#dim_overlay").length<1)
                        {
                                $(document.body).append("<div id='dim_overlay'></div>");
                                $("#dim_overlay").show();
                        }
                        if($("#dialog_box").length<1)
                        {
                                $(document.body).append("<div id='dialog_box' style='display:none;'></div>");
                        }
                        $("#dialog_box").html(xml).show();
                }
        });
}

function show_feed_content_more(obj)
{
	var obj_parent = $(obj).parents(".feed-item-more-switch");
	$(obj_parent).siblings(".feed-item-more").toggle();
	if($(obj_parent).siblings(".feed-item-more").css('display')=="none")
		$(obj).html('&raquo; view all');
	else
		$(obj).html('&raquo; hide');
		
}

function report_post_abuse(post_id, type)
{
	if($("#abuse_post_id").length>0)
		$("#abuse_post_id").val(post_id);
	else
		$(document.body).append('<input	type="hidden" id="abuse_post_id" name="abuse_post_id" value="'+post_id+'"	/>');
	
	if($("#member_logged_in").val()=="yes")
	{
		show_report_abuse_dialog();
	} else
	{
		show_login_dialog("show_report_abuse_dialog");
	}
}

function show_report_abuse_dialog()
{
	var post_id = $("#abuse_post_id").val();
	$.ajax({
		type: "POST",
		url: "/common/dialog/report-abuse/",
		data: {
			post_id: post_id,
			request_type: "show_report_abuse_dialog"
		},
		beforeSend: function(){
			show_dialog_loading();
		},
		success: function(xml){
			$(document.body).append("<div id='dim_overlay'></div>");
			$("#dim_overlay").show();
			if($("#dialog_box").length<1)
			{
				$(document.body).append("<div id='dialog_box' style='display:none;'></div>");
			}
			$("#dialog_box").html(xml).show();
		}
	});
}