jQuery.log = function(message) {
   if(window.console) {
       console.debug(message);
   } else {
      //alert(message);
    //document.write(message);
   }
};
	(function($){
	 var startDate;
	 var endDate;
	 var count={};
	 $.startTimer=function(){
	  startDate=new Date();
	 };
	 $.logTime=function(){
	  endDate=new Date();
	  $.log(endDate-startDate);
	 };
	 $.getTime=function(){
	  endDate=new Date();
	  return endDate-startDate;
	 };
	 $.addCount = function(to, nr, node){if (!count[to]) count[to]=0; count[to]=count[to]+nr;$.log(nr);$.log(node);};
	 $.logCount = function(){$.log(count);};
	})(jQuery);
$.startTimer(); 
$.logTime();

function isValidUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return regexp.test(s);
};

function _fakefile(){
	//file upload
	$('#upload').unbind('change');
	$('#upload').change(function(event){
		$('#fakeinput').val($(this).val());
		$('#upload_photo_button').removeAttr("disabled");
		$('#upload_photo_button').removeClass("disabled");
	});
}

var BonusChecker={
	Admin_Bonus_add:function(){
		$("#x_bonus_brand").change(function(event){
			//alert($("#x_bonus_brand option:selected").val());
			$.post('admin/bonus/get-categories/',{id:$("#x_bonus_brand option:selected").val()},function(resp){
				$("#x_categories").html('');
				//alert(resp.success);
				var label = '<label>Categories</label>';
				$.each(resp.data, function(k,v){
					$("#x_categories").append(label+'<input type="radio" name="bonus[category]" value="'+v.id+'" /><span class = "radio">'+v.name+'</span><br class="clear" />');
					label = '<label></label>';
				});
			},'json');
		});
	},
	Affiliate_Bonus_Page_filter:function(){
		$("#display_all").click(function(event){
			if ($("#display_all").attr("checked")){
				$("#single_merchant").hide(1000);
			}
			else{
				$("#single_merchant").show(1000);
			}
		});
	},
//	Merchant_add_bonus:function(){
//		$("#brand").change(function(event){
//			$.post('merchant/get-category/',{id:$("#brand option:selected").val()},function(resp){
//				$("#x_category").val(resp.data);
//			},'json');
//		});
//	},
	Home_Page_login:function(){
		$("#merchant_email").focus(function(event){
			$("#merchant_email").val("");
		});
		$("#affiliate_email").focus(function(event){
			$("#affiliate_email").val("");
		});
		$("#merchant_pass").focus(function(event){
			$("#merchant_pass").replaceWith('<input id="merchant_pass" type="password" name="login[pass]" value = ""/>');
			$("#merchant_pass").focus();
		});
		$("#affiliate_pass").focus(function(event){
			$("#affiliate_pass").replaceWith('<input id="affiliate_pass" type="password" name="login[pass]" value = ""/>');
			$("#affiliate_pass").focus();
		});
	},
	Forgot_Password_email:function(){
		$("#forgot_pass_email").focus(function(event){
			$("#forgot_pass_email").val("");
		});
	},
	Merchant_Account_focus_url_input:function(){
		$("#url").focus(function(event){
			$("#url").val("");
			$("#url").removeClass('italic');
		});
		$("#affiliate_url").focus(function(event){
			$("#affiliate_url").val("");
			$("#affiliate_url").removeClass('italic');
		});
	},
	Login_merchant:function(){
		$("#merchant_login_button").click(function(event){
			event.preventDefault();
			$.post('login/merchant', 
				{'login_merchant[email]':$('input[name="login_merchant[email]"]').val(),'login_merchant[pass]':$('#merchant_pass').val()},
				function(resp){
					if(resp.success){
						//redirect to bonus page
						window.location = "merchant/bonus-page";
					}else{
						//show errors
						$("#merchant_error").html(
						'<span class="error">'+resp.reason+
						'</span><br class = "clear" />'
						);
					}
				},'json'
			);
		});
	},
	Login_affiliate:function(){
		$("#affiliate_login_button").click(function(event){
			event.preventDefault();
			$.post('login/affiliate', 
				{'login[email]':$('input[name="login_affiliate[email]"]').val(),'login[pass]':$('#affiliate_pass').val()},
				function(resp){
					if(resp.success){
						//redirect to bonus page
						window.location = "affiliate/bonus-page";
					}else{
						//show errors
						$("#affiliate_error").html(
						'<span class="error">'+resp.reason+
						'</span><br class = "clear" />'
						);
					}
				},'json'
			);
		});
	},
	Merchant_select_bonus_type_on_load:function(){
		//used in addBonusAction
		if ($("#bonus_type option:selected").val()=="2"){
			$("#event_types").show(1000);
			if ($("#event_type option:selected").val()=="0"){
				$("#multiple_day_event_details").hide(1000);
				$("#single_day_event_details").show(1000);
			}else{
				$("#single_day_event_details").hide(1000);
				$("#multiple_day_event_details").show(1000);
			}
		}else{
			$("#event_types").hide(1000);
			$("#single_day_event_details").hide(1000);
			$("#multiple_day_event_details").hide(1000);
		}
	},
	Merchant_select_bonus_type:function(){
		//used in addBonusAction
		$("#bonus_type").change(function(event){
			if ($("#bonus_type option:selected").val()=="2"){
				$("#event_types").show(1000);
				if ($("#event_type option:selected").val()=="0"){
					$("#multiple_day_event_details").hide(1000);
					$("#single_day_event_details").show(1000);
				}else{
					$("#single_day_event_details").hide(1000);
					$("#multiple_day_event_details").show(1000);
				}
			}else{
				$("#event_types").hide(1000);
				$("#single_day_event_details").hide(1000);
				$("#multiple_day_event_details").hide(1000);
			}
		});
	},
	Merchant_select_event_type:function(){
		//used in addBonusAction
		$("#event_type").change(function(event){
			if ($("#event_type option:selected").val()=="0"){
				$("#multiple_day_event_details").hide(1000);
				$("#single_day_event_details").show(1000);
			}else{
				$("#single_day_event_details").hide(1000);
				$("#multiple_day_event_details").show(1000);
			}
		});
	},
	News_number_of_news_change:function(){
		//used in addBonusAction
		$("#news_number").change(function(event){
			window.location= "news/index?page="+$('#news_page_numbers .pg-number').text()+"&count="+$("#news_number option:selected").val();
		});
	},
	Bonus_Page_hide_filter:function(){
		$("#hide a").click(function(event){
			event.preventDefault();
			$("div.filters-container div.content").hide();
			$("div.filters-container div.brands-filters-content").hide(); //admin/brand/view-all
			$("#hide").hide();
			$("#show").show();
		});
		$("#show a").click(function(event){
			event.preventDefault();
			$("div.filters-container div.content").show();
			$("div.filters-container div.brands-filters-content").show();
			$("#show").hide();
			$("#hide").show();
			
		});
	},
	Page_hide_box:function(){
		$(".hide a").click(function(event){
			event.preventDefault();
			var id = this.href.split("#")[1];
			$("div.hideable #content-"+id).hide();
			$("#hide-"+id).hide();
			$("#show-"+id).show();
			if (id == 3){
				$(".explanation").hide();
			}
		});
		$(".show a").click(function(event){
			event.preventDefault();
			var id = this.href.split("#")[1];
			$("div.hideable #content-"+id).show();
			$("#show-"+id).hide();
			$("#hide-"+id).show();
			if (id == 3){
				$(".explanation").show();
			}
		});
	},
	Bonus_Page_hide_description:function(){
		$(".open_description").click(function(event){
			event.preventDefault();
			var id = this.href.split("#")[1];
			$("#description-"+id).show();
			$("#bonus-"+id).hide();
			
		});
		$(".close_description").click(function(event){
			event.preventDefault();
			var id = this.href.split("#")[1];
			$("#description-"+id).hide();
			$("#bonus-"+id).show();
			
		});
	},
	Affiliate_Account_select_all_bonus_types:function(){
		$(".brands-container table tr td a").click(function(event){
			event.preventDefault();
			var row=$($(this).parents('tr')[0]);
			if ($(row.find('input')[0]).attr('checked')){
				row.find('input').removeAttr('checked');
				row.find('label').removeClass('checked');
			}else {
				row.find('input').attr('checked','checked');
				row.find('label').addClass('checked');
			}
		});
	},
	Merchant_Account_delete_bonus:function(){
		$(".popup").live('click',function(event){
			var _this = $(this);
			var id = ($(this).attr('href')).split('#')[1];
			event.preventDefault();
			$('#popupContact').dialog({
				autoOpen: false,
				width: 420,
				bgiframe: true,
				modal: true,
				resizable:false,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				close: function(ev, ui) { $(this).dialog('destroy'); }
			});
			$('#popupContact').dialog('open');
		
			$("#contactArea a.delete").click(function(event){
				event.preventDefault();
				$('#popupContact').dialog("close"); 
				$('#popupContact').dialog("destroy");
				window.location = 'bonus/delete?id='+id;
				
			});
			$("#contactArea a.remove").click(function(event){
				event.preventDefault();
				$('#popupContact').dialog("close"); 
				$('#popupContact').dialog("destroy");
				window.location = 'bonus/remove?id='+id;
			});
		});
	},
	Admin_delete_bonus:function(){
		$(".admin-popup").live('click',function(event){
			var _this = $(this);
			var id = ($(this).attr('href')).split('#')[1];
			event.preventDefault();
			$('#popupContact').dialog({
				autoOpen: false,
				width: 420,
				bgiframe: true,
				modal: true,
				resizable:false,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				close: function(ev, ui) { $(this).dialog('destroy'); }
			});
			$('#popupContact').dialog('open');
		
			$("#contactArea a.delete").click(function(event){
				event.preventDefault();
				$('#popupContact').dialog("close"); 
				$('#popupContact').dialog("destroy");
				window.location = 'admin/bonus/delete?id='+id;
				
			});
			$("#contactArea a.remove").click(function(event){
				event.preventDefault();
				$('#popupContact').dialog("close"); 
				$('#popupContact').dialog("destroy");
				window.location = 'admin/bonus/remove?id='+id;
			});
		});
	},
	Admin_delete_third_party:function(){
		$(".delete-third-party-popup").click(function(event){
			event.preventDefault();
			var _this = $(this);
			$("#dialog").dialog({
				bgiframe: true,
				resizable: false,
				height:140,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					'Delete 3rd party': function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						window.location = _this.attr('href');
					},
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					}
				}
			});
			$('#dialog').dialog('open');
		});
	},
	Admin_add_third_party_review:function(container, url){
		$(container+" .add-third-party-review").live('click',function(event){
			$('#tips').html('<span>Select a 3rd Party:</span>');
			$('#review_url').val('');
			event.preventDefault();
			var _this = $(this);
			var thirdParty = $("#third_party");
			
			$("#dialog").dialog({
				bgiframe: true,
				autoOpen: false,
				width: 420,
				modal: true,
				buttons: {
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					},
					'Add 3rd Party Review': function() {
						var reviewUrl = $('#review_url').val();
						if (isValidUrl(reviewUrl)){
							var id = _this.attr('href').split("#")[1];
							$.post(url,{id: id,third_party_id:$("#third_party option:selected").val(),review_url:reviewUrl},function(resp){
								v = resp.data;
								if (resp.success){
									//show the icon
									$('#item_'+id).append('<a target = "_blank" class = "review" id="'+$("#third_party option:selected").val()+'" href ="'+reviewUrl+'" title = "'+$("#name").html()+'" ><img src = "display/photo/?src='+$('#logo a').attr('href')+'&h=18" /></a>');
									//$('#tips').html('ok');
									$("#dialog").dialog('close');
									$("#dialog").dialog('destroy');
								}
								else{
									//show the error
									$('#tips').html('<p class = "red">'+resp.error+'</p>');
								}
							},'json');
						}else $('#tips').html('<p class = "red">You must enter a valid url!</p>');
					}
				}
			});
			$('#dialog').dialog('open');
		});
		$("#third_party").change(function(event){
			$.post('admin/third-parties/json-get-third-party/',{id:$("#third_party option:selected").val()},function(resp){
				if (resp.success){
					v = resp.data;
					$("#name").html(v.name);
					$("#description").html(v.description);
					$("#url").html('<a href = "'+v.url+'">'+v.url+'</a>');
					$("#logo").html('<a href = "'+v.logo_file_link+'"><img src = "display/photo/?h=30&src='+v.logo_file_link+'" /></a>');
				}else{
					$('#tips').html('There are no 3rd parties at the moment.');
				}
			},'json');
		});
	},
	Affiliate_report_an_error:function(){
		$(".error").click(function(event){
			event.preventDefault();
			var _this = $(this);
			$("#dialog").dialog({
				bgiframe: true,
				resizable: false,
				height:140,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					Ok: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						var id = _this.attr('href').split("#")[1];
						var bonus = [];
						var labels = $('#description-'+id+' .general-information label');
						labels.each(function(){
							var t = $(this).next('span').html();
							bonus[$(this).attr('for')] = t.trim();
						});	
						$.post('affiliate/json-send-error-report/',{content:$('#description-'+id+' .general-information').html()+$('#description-'+id+' .description').html()},function(resp){
							$("#dialog2").dialog({
								bgiframe: true,
								resizable: false,
								height:140,
								modal: true,
								overlay: {
									backgroundColor: '#000',
									opacity: 0.5
								},
								buttons: {
									Ok: function() {
										$(this).dialog('close');
										$(this).dialog('destroy');
									}
								}
							});
							$('#dialog2').dialog('open');
						},'json');
					},
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					}
				}
			});
			$('#dialog').dialog('open');
		});
	},
	Affiliate_add_special_subscribe:function(){
		$(".special-subscribe").click(function(event){
			event.preventDefault();
			var _this = $(this);
			$("#dialog3").dialog({
				bgiframe: true,
				resizable: false,
				height:140,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					Ok: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						var bonusId = _this.attr('href').split("#")[1];
						var bonus = [];
						$.post('affiliate/json-add-priority-subscription/',{id:bonusId},function(resp){
							if (resp.success){
								if ($('#bonus-'+bonusId).hasClass('odd'))
									$('#bonus-'+bonusId).addClass('light-pink');
								if ($('#bonus-'+bonusId).hasClass('even'))
									$('#bonus-'+bonusId).addClass('pink');
								$('#description-'+bonusId+' .special-subscribe').hide();
								$('#description-'+bonusId+' .special-unsubscribe').show();
							}
							$('#dialog4 p').html(resp.message);
							$("#dialog4").dialog({
								bgiframe: true,
								resizable: false,
								height:140,
								modal: true,
								overlay: {
									backgroundColor: '#000',
									opacity: 0.5
								},
								buttons: {
									Ok: function() {
										$(this).dialog('close');
										$(this).dialog('destroy');
									}
								}
							});
							$('#dialog4').dialog('open');
						},'json');
					},
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					}
				}
			});
			$('#dialog3').dialog('open');
		});
	},
	Affiliate_remove_special_subscribe:function(){
		$(".special-unsubscribe").click(function(event){
			event.preventDefault();
			var _this = $(this);
			$("#dialog5").dialog({
				bgiframe: true,
				resizable: false,
				height:140,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					'Yes': function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						var bonusId = _this.attr('href').split("#")[1];
						var bonus = [];
						$.post('affiliate/json-remove-priority-subscription/',{id:bonusId},function(resp){
							if (resp.success){
								$('#bonus-'+bonusId).removeClass('light-pink').removeClass('pink');
									
								$('#description-'+bonusId+' .special-unsubscribe').hide();
								$('#description-'+bonusId+' .special-subscribe').show();
							}
							$('#dialog4 p').html(resp.message);
							$("#dialog4").dialog({
								bgiframe: true,
								resizable: false,
								height:140,
								modal: true,
								overlay: {
									backgroundColor: '#000',
									opacity: 0.5
								},
								buttons: {
									Ok: function() {
										$(this).dialog('close');
										$(this).dialog('destroy');
									}
								}
							});
							$('#dialog4').dialog('open');
						},'json');
					},
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					}
				}
			});
			$('#dialog3').dialog('open');
		});
	},
	Admin_delete_review:function(container,url){
		$(container+" .review").live("click",function(event){
			event.preventDefault();
			var _this = $(this);
			$("#dialog_delete_review").dialog({
				bgiframe: true,
				resizable: false,
				height:180,
				width:380,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					},
					'Delete':function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						var thirdPartyId = _this.attr('id');
						var brandId = _this.parent().attr('id').split('_')[1];
						$.post(url,{id: brandId,third_party_id : thirdPartyId},function(resp){
							if (resp.success){
								//window.location = "admin/brand/view-all";
								//remove the icon
								$('#item_'+brandId+' a[id='+thirdPartyId+']').remove();
								$("#dialog").dialog('close');
								$("#dialog").dialog('destroy');
							}
							else{
								//show the error
								$('#review_tips').html('<p class = "red">'+resp.error+'</p>');
							}
						},'json');
					},
					'Save':function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						var thirdPartyId = _this.attr('id');
						var brandId = _this.parent().attr('id').split('_')[1];
						BonusChecker.Admin_new_url_review(container,brandId,thirdPartyId);
					},
					'Follow Link': function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						window.open(_this.attr('href'));
					}
				}
			});
			$('#dialog_delete_review').dialog('open');
		});
	},
	Admin_new_url_review:function(container,id,thirdPartyId){
		$("#dialog_new_review").dialog({
			bgiframe: true,
			resizable: false,
			height:120,
			width:260,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
					$(this).dialog('destroy');
				},
				'Save':function() {
					var reviewUrl = $('#new_review_url').val();
					if (isValidUrl(reviewUrl)){
						if (container == '.brand-review'){ 
							var url = 'admin/brand/change-url-review';
							var redirect = 'admin/brand/view-all';
						}
						else if (container == '.affiliate-program-review'){
							var url = 'admin/merchant/change-url-review';
							var redirect = 'admin/merchant/affiliate-programs';
						}
						$.post(url,{id: id,third_party_id:thirdPartyId,review_url:reviewUrl},function(resp){
							v = resp.data;
							if (resp.success){
								$("#dialog_new_review").dialog('close');
								$("#dialog_new_review").dialog('destroy');
								window.location = redirect;
							}
							else{
								//show the error
								$('#new_url_tips').html('<p class = "red">'+resp.error+'</p>');
							}
						},'json');
					}else $('#new_url_tips').html('<p class = "red">You must enter a valid url!</p>');
				}
			}
		});
		$('#dialog_new_review').dialog('open');
	},
	Merchant_delete_brand:function(){
		$(".delete-brand").live("click",function(event){
			event.preventDefault();
			var _this = $(this);
			$("#delete_brand").dialog({
				bgiframe: true,
				resizable: false,
				draggable:false,
				height:100,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					Ok: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
						window.location = _this.attr("href");
					},
					Cancel: function() {
						$(this).dialog('close');
						$(this).dialog('destroy');
					}
				}
			});
			$('#delete_brand').dialog('open');
		});
	}
};

	
	
$(function() {
	$.logTime();
	$('.span_set').tooltip();
	BonusChecker.Admin_Bonus_add();
	BonusChecker.Affiliate_Bonus_Page_filter();
	BonusChecker.Home_Page_login();
	BonusChecker.Forgot_Password_email();
	BonusChecker.Merchant_select_bonus_type_on_load();
	BonusChecker.Merchant_select_bonus_type();
	BonusChecker.Merchant_select_event_type();
	BonusChecker.Login_merchant();
	BonusChecker.Login_affiliate();
	BonusChecker.News_number_of_news_change();
	$(".datepicker").datepicker({ dateFormat: 'm/d/yy' });
	BonusChecker.Bonus_Page_hide_filter();
	BonusChecker.Bonus_Page_hide_description();
	BonusChecker.Page_hide_box();
	BonusChecker.Affiliate_Account_select_all_bonus_types();
	BonusChecker.Merchant_Account_focus_url_input();
	BonusChecker.Merchant_Account_delete_bonus();
	BonusChecker.Admin_delete_bonus();
	BonusChecker.Admin_delete_third_party();
	BonusChecker.Admin_add_third_party_review('.brand-review','admin/brand/add-third-party-review');
	BonusChecker.Admin_add_third_party_review('.affiliate-program-review','admin/merchant/add-third-party-review');
	BonusChecker.Affiliate_report_an_error();
	BonusChecker.Affiliate_add_special_subscribe();
	BonusChecker.Affiliate_remove_special_subscribe();
	BonusChecker.Admin_delete_review('.brand-review','admin/brand/remove-third-party-review');
	BonusChecker.Admin_delete_review('.affiliate-program-review','admin/merchant/remove-third-party-review');
	BonusChecker.Merchant_delete_brand();
	_fakefile();
	
	$(".custom-checks input[type='checkbox'], .custom-radios input[type='radio']").live('click', function(event){
		var input = $(this);
		var label = $('label[for='+input.attr('id')+']');
		if (input.is(':checked')) {
			if (input.is(':radio')) {			
				var allInputs = $("input[name='"+input.attr('name')+"']");
				allInputs.each(function(){
					$('label[for='+$(this).attr('id')+']').removeClass('checked');
				});		
			};
			label.addClass('checked');
		}
		else { label.removeClass('checked'); }
	});
	$(".custom-checks input[type='checkbox']:checked, .custom-radios input[type='radio']:checked").next('label').addClass('checked');
});
