var Util =
{
	dialog:
	{
		buildProductBoxHtml: function (p)
		{
			var name = decodeURIComponent(p.name);
			var size = p.size ? decodeURIComponent(p.size) : null;
			var ref_no = p.ref_no ? decodeURIComponent(p.ref_no) : null;
			var price = p.price ? decodeURIComponent(p.price) : null;
			
			var h = [];
			
			h.push("<div class='enquiry-row'>");
			h.push("	<div class='photo'><table class='centered-table' cellspacing='0' cellpadding='0'><tr align='center' vAlign='middle'><td><a href='"+p.link+"'><img src='"+p.photo+"' /></a></td></tr></table></div>");
			h.push("	<div class='info'>");
			h.push("		<div class='top'>");
			h.push("			<div class='name bold'><a href='"+p.link+"'>"+name+"</a></div>");
			h.push("			<div class='sub-text'>");
			// if (detail)
				// h.push("				<div class='detail'>"+detail+"</div>");
			if (size)
				h.push("				<div class='size'>size: "+size+"</div>");
			if (ref_no)
				h.push("				<div class='ref_no'>ref # "+ref_no+"</div>");
			h.push("			</div>");
			h.push("		</div>");
			h.push("		<div class='bottom'>");
			if (price)
			{
				h.push("			<div class='price bold'>$"+price+"</div>");
			}
			h.push("		</div>");
			h.push("	</div>");
			h.push("	<div class='clear'></div>");
			h.push("</div>");
			
			return h.join('\n');
		}
	},
	
	shareOnFacebook: function (u)
	{
		if (typeof u == 'undefined')
			u = encodeURIComponent(location.href);
			
		var t = encodeURIComponent(document.title);
		
		window.open('http://www.facebook.com/sharer.php?u='+u+'&t='+t,'sharer','toolbar=0,status=0,width=626,height=436');
	},
	
	openWindow: function (url, w, h, window_name)
	{
		if (typeof window_name == 'undefined')
		{
			window_name = '';
		}
		
		window.open(url, window_name, "toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=yes, resizable=no, width=" + w + ", height=" + h + ", left=" + ((window.screen.availWidth - (w + 4)) / 2) + ", top=" + ((window.screen.availHeight - (h + 50)) / 2));
	}
}

var RoundedDialog = function (target_id)
{
	this.target = $('#'+target_id);
	this.dialog_structure = null;
	this.constructDialog();
}
RoundedDialog.prototype =
{
	constructDialog: function ()
	{
		var h = [];
		h.push('<div class="dialog-structure">');
		h.push('<div class="close-btn"></div>');
		h.push('<div class="border top"></div>');
		h.push('<div class="border bottom"></div>');
		h.push('<div class="border left"></div>');
		h.push('<div class="border right"></div>');
		h.push('<div class="corner top-left"></div>');
		h.push('<div class="corner top-right"></div>');
		h.push('<div class="corner bottom-left"></div>');
		h.push('<div class="corner bottom-right"></div>');
		h.push('</div>');
		this.target.append(h.join(''));
		
		this.dialog_structure = this.target.children('.dialog-structure');
		this.reformDialog();
	},
	
	reformDialog: function () // set the dialog height and width
	{
		var wrapper = this.target.children('.dialog-wrapper');
		var w = parseInt(wrapper.css('width').replace('px', ''));
		var h = parseInt(wrapper.css('height').replace('px', ''));
		
		wrapper.children('.content-wrapper')
			.css('height', h-30);
		
		this.dialog_structure
			.children('.top, .bottom').width(w)
			.end()
			.children('.right, .left').height(h);
		
		var target = this.target;
		this.dialog_structure.children('.close-btn').click(function () { target.hide(); });
	},
	
	show: function ()
	{
		var min_top = this.target.parent().position().top;
		var scroll_top = $(document).scrollTop();
		var top_diff = scroll_top - min_top;
		if (top_diff > 0)
		{
			this.target.css('top', top_diff);
		}
		else
		{
			this.target.css('top', 0);
		}
			
		this.target.show();
	},
	
	hide: function ()
	{
		this.target.hide();
	}
};

var EnquiryDialog = function (target_id)
{
	this.init(target_id);
}
EnquiryDialog.prototype =
{
	init: function (target_id)
	{
		this.target = $('#'+target_id);
		
		// move dialog model to target area
		this.dialog_model = $('#enquiry-dialog-model');
		this.target.append(this.dialog_model.children('.dialog-wrapper'));
		
		// new RoundedDialog
		this.dialog_frame = new RoundedDialog(this.target.attr('id'));
		
		// event
		var target = this.target;
		$('#enquiry-controls img[src*=btn_reset]', this.target).click(function () {
			$('#enquiry-form', target)[0].reset();
		});
	},
	
	showDialog: function (resp)
	{
		var items = resp.items;
		
		var p = null;
		if (items.length == 1)
			p = items[0];
		else
			return;
			
		$('#enquiry-hidden-val input[name=enquiry_email]', this.target).val(decodeURIComponent(p.email));
		$('#enquiry-hidden-val input[name=item_type]', this.target).val(p.type);
		$('#enquiry-hidden-val input[name=product_id]', this.target).val(p.pid);
		$('#enquiry-biz span[name=biz_name]', this.target).html(decodeURIComponent(p.biz_name));
		
		$('#enquiry-item .item').html(Util.dialog.buildProductBoxHtml(p));
		
		// events
		var target = this.target;
		$('#enquiry-controls img[src*=btn_submit]', this.target).click($.hitch(this, 'submitEnquiry'));
		$('.dialog-wrapper .content-wrapper .success-msg .close-btn img', this.target).click(function () {
			target.hide();
		});
		
		$('.dialog-wrapper .content-wrapper', this.target)
			.children('.content').show()
			.end()
			.children('.success-msg').hide();
		
		this.show();
	},
	
	validateEnquiryForm: function ()
	{
		if (
			$.trim($('#enquiry-form input[name=name]', this.target).val()) == ''
			|| $.trim($('#enquiry-form input[name=email]', this.target).val()) == ''
		)
		{
			alert('Please fill in the required fields (with *).');
			return false;
		}
		
		return true;
	},
	
	submitEnquiry: function ()
	{
		if (!this.validateEnquiryForm())
			return;
		else
			$('#enquiry-controls img[src*=btn_submit]', this.target).unbind('click');
		
		var data = $('#enquiry-form', this.target).serializeArray();
		var url = '/application/req/send_enquiry.php';

		data.push( { name:'biz_name', value:$('#enquiry-biz span[name=biz_name]', this.target).html() } );

		$.post(url, data, $.hitch(this, 'afterSentEnquiry'), 'json');
	},
	
	afterSentEnquiry: function (resp)
	{
		if (resp.is_sent)
		{
			var biz_name = $('#enquiry-biz span[name=biz_name]', this.target).html();
			$('.dialog-wrapper .content-wrapper', this.target)
				.children('.content').hide()
				.end()
				.children('.success-msg')
					.children('.biz-name').html(biz_name)
					.end()
				.show();
		}
	},
	
	show: function ()
	{
		this.dialog_frame.show();
		// this.target.show();
	},
	
	hide: function ()
	{
		this.dialog_frame.hide();
		// this.target.hide();
	}
}

var SharingDialog = function (target_id)
{
	this.init(target_id);
}
SharingDialog.prototype =
{
	init: function (target_id)
	{
		this.target = $('#'+target_id);
		
		// move dialog model to target area
		this.dialog_model = $('#share-dialog-model');
		this.target.append(this.dialog_model.children('.dialog-wrapper'));
		
		// new RoundedDialog
		this.dialog_frame = new RoundedDialog(this.target.attr('id'));
		
		// event
		var target = this.target;
		// click event for dialogs reset button
		$('#share-controls img[src*=btn_reset]', this.target).click(function () {
			$('#share-form', target)[0].reset();
		});
		
		// share dialog - no. of recipients change()
		$('.dialog-wrapper .no-of-recipients select', this.target).change(function () {
			var max_fds = 5;
			var first_idx_to_hide = $(this).val();
			
			var fd_names = $('.fd-names', target).children();
			var fd_emails = $('.fd-emails', target).children();
			for (var i = 1; i < max_fds; i++)
			{
				if (i >= first_idx_to_hide)
				{
					$(fd_names[i])
						.children().attr('disabled', true)
						.end()
						.hide();
					$(fd_emails[i])
						.children('input').attr('disabled', true)
						.end()
						.hide();
				}
				else
				{
					$(fd_names[i])
						.children('input').removeAttr('disabled')
						.end()
						.show();
					$(fd_emails[i])
						.children('input').removeAttr('disabled')
						.end()
						.show();
				}
			}
		});
	},
	
	showDialog: function (resp)
	{
		var items = resp.items;
		
		var p = null;
		if (items.length == 1)
			p = items[0];
		else
			return;
			
		$('#share-hidden-val input[name=item_type]', this.target).val(p.type);
		$('#share-hidden-val input[name=product_id]', this.target).val(p.pid);
		
		$('#share-item .item', this.target).html(Util.dialog.buildProductBoxHtml(p));
		
		// click event for submit
		var target = this.target;
		$('#share-controls img[src*=btn_submit]', this.target).click($.hitch(this, 'submitSharing'));
		$('.dialog-wrapper .content-wrapper .success-msg .close-btn img', this.target).click(function () {
			target.hide();
		});
		
		$('.dialog-wrapper .content-wrapper', this.target)
			.children('.content').show()
			.end()
			.children('.success-msg').hide();
		
		this.show();
	},
	
	validateSharingForm: function ()
	{
		if (
			$.trim($('#share-form input[name=name]', this.target).val()) == ''
			|| $.trim($('#share-form input[name=email]', this.target).val()) == ''
			|| $.trim($('.dialog-wrapper .fd-names input[name=fd_name[]]:enabled:first', this.target).val()) == ''
			|| $.trim($('.dialog-wrapper .fd-emails input[name=fd_email[]]:enabled:first', this.target).val()) == ''
		)
		{
			alert('Please fill in the required fields (with *).');
			return false;
		}
		
		return true;
	},
	
	submitSharing: function ()
	{
		if (!this.validateSharingForm())
			return;
		else
			$('#share-controls img[src*=btn_submit]', this.target).unbind('click');
		
		var data = $('#share-form', this.target).serializeArray();
		var url = '/application/req/send_sharing.php';

		$.post(url, data, $.hitch(this, 'afterSentSharing'), 'json');
	},
	
	afterSentSharing: function (resp)
	{
		if (resp.is_sent)
		{
			var fd_names = $('.dialog-wrapper .fd-names input[name=fd_name[]]:enabled', this.target);
			var fd_emails = $('.dialog-wrapper .fd-emails input[name=fd_email[]]:enabled', this.target);
			var recipient_htmls = [];
			fd_names.each(function (i) {
				var name = $.trim(this.value);
				var email = $.trim(fd_emails[i].value);
				if (name != '' && email != '')
				{
					recipient_htmls.push('<div>'+name+' &lt;'+email+'&gt;</div>');
				}
			});
			
			$('.dialog-wrapper .content-wrapper', this.target)
				.children('.content').hide()
				.end()
				.children('.success-msg')
					.children('.fds').html(recipient_htmls.join('\n'))
					.end()
				.show();
		}
	},

	show: function ()
	{
		this.dialog_frame.show();
		// this.target.show();
	},
	
	hide: function ()
	{
		this.target.hide();
	}
}

var BizEnquiryDialog = function (target_id)
{
	this.init(target_id);
}
BizEnquiryDialog.prototype =
{
	init: function (target_id)
	{
		this.target = $('#'+target_id);
		
		// move dialog model to target area
		this.dialog_model = $('#biz-enquiry-dialog-model');
		this.target.append(this.dialog_model.children('.dialog-wrapper'));
		
		// new RoundedDialog
		this.dialog_frame = new RoundedDialog(this.target.attr('id'));
		
		// event
		var target = this.target;
		$('#biz-enquiry-controls img[src*=btn_reset]', this.target).click(function () {
			$('#biz-enquiry-form', target)[0].reset();
		});
	},
	
	showDialog: function (biz)
	{
		$('#biz-enquiry-hidden-val input[name=biz_id]', this.target).val(biz.biz_id);
		$('#biz-enquiry-biz span[name=biz_name]', this.target).html(biz.biz_name);
		
		// events
		var target = this.target;
		$('#biz-enquiry-controls img[src*=btn_submit]', this.target).click($.hitch(this, 'submitEnquiry'));
		$('.dialog-wrapper .content-wrapper .success-msg .close-btn img', this.target).click(function () {
			target.hide();
		});
		
		$('.dialog-wrapper .content-wrapper', this.target)
			.children('.content').show()
			.end()
			.children('.success-msg').hide();
		
		this.show();
	},
	
	validateEnquiryForm: function ()
	{
		if (
			$.trim($('#biz-enquiry-form input[name=first_name]', this.target).val()) == ''
			|| $.trim($('#biz-enquiry-form input[name=last_name]', this.target).val()) == ''
			|| $.trim($('#biz-enquiry-form input[name=email]', this.target).val()) == ''
		)
		{
			alert('Please fill in the required fields (with *).');
			return false;
		}
		
		return true;
	},
	
	submitEnquiry: function ()
	{
		if (!this.validateEnquiryForm())
			return;
		else
			$('#biz-enquiry-controls img[src*=btn_submit]', this.target).unbind('click');
		
		var data = $('#biz-enquiry-form', this.target).serializeArray();
		var url = '/application/req/send_biz_enquiry.php';

		$.post(url, data, $.hitch(this, 'afterSentEnquiry'), 'json');
	},
	
	afterSentEnquiry: function (resp)
	{
		if (resp.is_sent)
		{
			var biz_name = $('#biz-enquiry-biz span[name=biz_name]', this.target).html();
			$('.dialog-wrapper .content-wrapper', this.target)
				.children('.content').hide()
				.end()
				.children('.success-msg')
					.children('.biz-name').html(biz_name)
					.end()
				.show();
		}
	},
	
	show: function ()
	{
		this.dialog_frame.show();
		// this.target.show();
	},
	
	hide: function ()
	{
		this.target.hide();
	}
}

var ShopSharingDialog = function (target_id)
{
	this.init(target_id);
}
ShopSharingDialog.prototype =
{
	init: function (target_id)
	{
		this.target = $('#'+target_id);
		
		// move dialog model to target area
		this.dialog_model = $('#shop-share-dialog-model');
		this.target.append(this.dialog_model.children('.dialog-wrapper'));
		
		// new RoundedDialog
		this.dialog_frame = new RoundedDialog(this.target.attr('id'));
		
		// event
		var target = this.target;
		// click event for dialogs reset button
		$('#shop-share-controls img[src*=btn_reset]', this.target).click(function () {
			$('#shop-share-form', target)[0].reset();
		});
		
		// share dialog - no. of recipients change()
		$('.dialog-wrapper .no-of-recipients select', this.target).change(function () {
			var max_fds = 5;
			var first_idx_to_hide = $(this).val();
			
			var fd_names = $('.fd-names', target).children();
			var fd_emails = $('.fd-emails', target).children();
			for (var i = 1; i < max_fds; i++)
			{
				if (i >= first_idx_to_hide)
				{
					$(fd_names[i])
						.children().attr('disabled', true)
						.end()
						.hide();
					$(fd_emails[i])
						.children('input').attr('disabled', true)
						.end()
						.hide();
				}
				else
				{
					$(fd_names[i])
						.children('input').removeAttr('disabled')
						.end()
						.show();
					$(fd_emails[i])
						.children('input').removeAttr('disabled')
						.end()
						.show();
				}
			}
		});
	},
	
	showDialog: function (info)
	{
		$('#shop-share-hidden-val input[name=item_id]', this.target).val(info.item_id);
		$('#shop-share-hidden-val input[name=item_type]', this.target).val(info.item_type);
		$('#shop-share-hidden-val input[name=shop_id]', this.target).val(info.shop_id);
		$('#shop-share-hidden-val input[name=section_id]', this.target).val(info.section_id);
		$('#shop-share-item .desc span.item_name', this.target).html(info.item_name);
		
		// click event for submit
		var target = this.target;
		$('#shop-share-controls img[src*=btn_submit]', this.target).click($.hitch(this, 'submitSharing'));
		$('.dialog-wrapper .content-wrapper .success-msg .close-btn img', this.target).click(function () {
			target.hide();
		});
		
		$('.dialog-wrapper .content-wrapper', this.target)
			.children('.content').show()
			.end()
			.children('.success-msg').hide();
		
		this.show();
	},
	
	validateSharingForm: function ()
	{
		if (
			$.trim($('#shop-share-form input[name=name]', this.target).val()) == ''
			|| $.trim($('#shop-share-form input[name=email]', this.target).val()) == ''
			|| $.trim($('.dialog-wrapper .fd-names input[name=fd_name[]]:enabled:first', this.target).val()) == ''
			|| $.trim($('.dialog-wrapper .fd-emails input[name=fd_email[]]:enabled:first', this.target).val()) == ''
		)
		{
			alert('Please fill in the required fields (with *).');
			return false;
		}
		
		return true;
	},
	
	submitSharing: function ()
	{
		if (!this.validateSharingForm())
			return;
		else
			$('#shop-share-controls img[src*=btn_submit]', this.target).unbind('click');
		
		var data = $('#shop-share-form', this.target).serializeArray();
		var url = '/application/req/send_shop_sharing.php';

		$.post(url, data, $.hitch(this, 'afterSentSharing'), 'json');
	},
	
	afterSentSharing: function (resp)
	{
		if (resp.is_sent)
		{
			var fd_names = $('.dialog-wrapper .fd-names input[name=fd_name[]]:enabled', this.target);
			var fd_emails = $('.dialog-wrapper .fd-emails input[name=fd_email[]]:enabled', this.target);
			var recipient_htmls = [];
			fd_names.each(function (i) {
				var name = $.trim(this.value);
				var email = $.trim(fd_emails[i].value);
				if (name != '' && email != '')
				{
					recipient_htmls.push('<div>'+name+' &lt;'+email+'&gt;</div>');
				}
			});
			
			$('.dialog-wrapper .content-wrapper', this.target)
				.children('.content').hide()
				.end()
				.children('.success-msg')
					.children('.fds').html(recipient_htmls.join('\n'))
					.end()
				.show();
		}
	},

	show: function ()
	{
		this.dialog_frame.show();
		// this.target.show();
	},
	
	hide: function ()
	{
		this.target.hide();
	}
}

// -- page-control ----------------------------------------------------------------------
$(function () {
	// Enter pressed
	$('div.page-control input[name=page]').keypress(function (e) {
		if (e.keyCode != 13)
			return;
			
		var to_page = parseInt(this.value);
		var page_ttl = parseInt($('div.page-control input:hidden[name=page-total]').val());
		var url = $('div.page-control input:hidden[name=page-url]').val();
		
		// not correct page
		if (isNaN(to_page) || to_page > page_ttl)
		{
			// alert('page number not exists');
			return;
		}
		
		window.location.href = url+'&page='+to_page;
	});
});
// --------------------------------------------------------------------------------------
