/**
* This file holds our jQuery module for secrets.com.  It will contain
* code for the forms and whatnot on this site.
*
* There should be NO code in this file that calls any of the functions
* contained herein by merely including this file.  Instead, calls to
* the functions here should happen from the template files. 
*
* @author Douglas Muth <dmuth@guesswho.com>
*/

/**
* Set our namespace for the function.
*/
jQuery.fn.secrets = function() {
}

jQuery.fn.secrets.main = function() {
 
	//
	// Focus on this element, if present.
	//
	$("#referral_id").focus();

	jQuery.fn.secrets.cvvHooks();
	jQuery.fn.secrets.passwordHiddenHook();
    jQuery.fn.secrets.campaignAddFormAdmin();
    jQuery.fn.secrets.campainList();
	jQuery.fn.secrets.itemHook();
    jQuery.fn.secrets.staff_formHook();
    jQuery.fn.secrets.agent_formHook();
    jQuery.fn.secrets.agent_listHook();
    jQuery.fn.secrets.loginHook();
    jQuery.fn.secrets.login_modal_buttonHook();
    jQuery.fn.secrets.prefHook();
    jQuery.fn.secrets.uiSidebarHooks();
    jQuery.fn.secrets.selectTextHooks();
    jQuery.fn.secrets.registrationHooks();
    jQuery.fn.secrets.no_referral_idHooks();
	jQuery.fn.secrets.royalties();
	jQuery.fn.secrets.payout_monthHooks();
	jQuery.fn.secrets.purchases_monthHooks();
    
} // End of main()

/**
* Set up code for purchases_monthHooks
* */
jQuery.fn.secrets.purchases_monthHooks = function(){

    $("#admin_purchase #purchases_month").change(function(){
        var $agent_id = $("#purchases_agent_id").val();
        var $month = $("#purchases_month").val();
       // alert($agent_id + " = " + $month);
        
		$.post(	"purchases.php", 
				{
				id: $agent_id,
				month: $month
				}, 
				function(data){
                   // alert(data);
					$("#admin_purchase tbody").html(data);
				}
		); // end post    
    }); // end click

}// end     jQuery.fn.secrets.purchases_monthHooks();


/**
* Set up code for payout_monthHooks
* */
jQuery.fn.secrets.payout_monthHooks = function(){

    $("#admin_payouts #payout_month").change(function(){
        var $agent_id = $("#payout_agent_id").val();
        var $month = $("#payout_month").val();
       // alert($agent_id + " = " + $month);
        
		$.post(	"payout.php", 
				{
				id: $agent_id,
				month: $month
				}, 
				function(data){
                   // alert(data);
					$("#admin_payouts tbody").html(data);
				}
		); // end post    
    }); // end click

}// end     jQuery.fn.secrets.payout_monthHooks();



/**
* Set up code for referral form
* */
jQuery.fn.secrets.no_referral_idHooks = function(){

    $("#referral #no_referral_id_btn").click(function(){
        $("#no_referral").toggle("slow") (display);
    
    }); // end click

}// end     jQuery.fn.secrets.no_referral_idHooks();


/**
* Set up code for registration form
* */
jQuery.fn.secrets.registrationHooks = function(){

    $("#toys_other").css("display", "none");
    
	//
	// IF we don't have a terms checkbox, stop here.
	//
	var terms = $("#terms").attr("name");
	if (!terms) {
		return(null);
	}

	//
	// A function within our function to update the status of the 
	// submit button based on tht terms.
	//
	var updateSubmitButton = function() {

		var termChecked = $('#terms:checked').val();
	
	    //
	    // terms checked
	    //
		if (termChecked != undefined){
			$('#submit_btn').removeAttr('disabled');
			$("#submit_btn_on").css("display", "block")
			$("#terms_error_off").css("display", "block")
			$("#submit_btn_off").css("display", "none")
            $("#terms_error_on").css("display", "none");

	    //
	    // terms not checked
	    //
		} else {
			$("#submit_btn_off").css("display", "block")
			$("#submit_btn_on").css("display", "none")
			$('#submit_btn').attr('disabled', 'disabled');
            $("#terms_error_off").css("display", "none");

		}

	} // End of updateSubmitButton()

	//
	// Always check our submit button when the intial page is loaded.
	//
	updateSubmitButton();

	//
	// Enable save button when terms are read and agreed to.
	//
	$("#registration_form").click(function(event){
	    var $target = $(event.target);

	    if($target.attr('id') == "terms"){
		    updateSubmitButton();
	    } // End if terms
	    else if($target.attr('id') == "submit_btn"){
	    
	        if($('#terms:checked').val() != undefined){
                if($("#country_code").val() != "840"
                    && $('#item_id_2').attr("checked") == true)
                {
                    alert("You cannot purchase Adult Toys outside of the U.S.A.");
	                return false;
	            }
	            return true;
	        }else{
	            return false;
	        }
	          
	    }// end if submit_btn
	    else if($target.attr('id') == "submit_btn_off"){

               $("#terms_error_on").addClass("error");
               $("#terms_error_on").css("display", "block");
               $("#terms_error_off").css("display", "none");
        
	    }// end if submit_btn_off
	    
    }); // End registration.click()


    
    $("#country_code").change(function(){
        updateProducts();
    });// end country_code.change
    
    
	var updateProducts = function() {
        if($("#country_code").val() != "840"){
            $("#toys_usa").css("display", "none");
            $("#toys_other").css("display", "block");
 	        $('#item_id_1').attr("checked", true);

        }else{
            $("#toys_usa").css("display", "block");
            $("#toys_other").css("display", "none");

        }
    
    }// end country_code.change

}// end registrationHooks



/**
* Highlight text where id = selectText
*
* some browsers do not allow the right-mouse click with just 
*   mouseover. user needs to click. So we have the additional 
*   step if necessary. It is attached to the body, so if the 
*   user can click outside of selectText and clean the selection
*
*/
jQuery.fn.secrets.selectTextHooks = function() {
    var $clicked = false;

	$("#selectText").mouseover(function(event){
        var $target = $(event.target);
        var $id = $target.attr('id');
	    selectText_select($id);
    }); // end selectText.mouseover

	$("body").click(function(event){
        var $target = $(event.target);
        var $id = $target.attr('id');
        if($id == "selectText"){
            $clicked = true;
            selectText_select($id);
        }else{
            $clicked = false;
        }
    }); // end body.click

	$("#selectText").mouseout(function(event){
	    if(! $clicked){
            selectText_clear();
        }
    }); // end selectLink.mouseout
    
   function  selectText_select($id){

		selectText_clear();
		if (document.selection) {
		    var range = document.body.createTextRange();
 	        range.moveToElementText(document.getElementById($id));
		    range.select();
		}else if (window.getSelection) {
		    var range = document.createRange();
		    range.selectNode(document.getElementById($id));
		    window.getSelection().addRange(range);
		}
    }

   function selectText_clear() {
		if (document.selection){
		    document.selection.empty(); 
		}else if (window.getSelection){
		    window.getSelection().removeAllRanges();
		}
	}


} // End of selectLinkHooks()

/**
* Set up hooks for ui sidebar links to HM and Sextoys
*/
jQuery.fn.secrets.uiSidebarHooks = function() {

	$("#ui_sidebar").click(function(event){
        var $target = $(event.target);
        var $message_id = "#" + $target.attr('id') + "_message";
        var $message = $($message_id).val();
        var $url_id = "#" + $target.attr('id') + "_url";
        var $url = $($url_id).val();
        var $output = true;
        
	    if($message){
	        $output = confirm($message);
        }
        
        return $output;
        
    }); // end ui_sidebar.click

} // End of cvvHooks()

/**
* Set up hooks for CVV checkbox.
*/
jQuery.fn.secrets.cvvHooks = function() {

	//
	// Add hooks for CVV link.
	//
	$("#cvv_howto_link").click(function(){
		$("#cvv_howto").css("display", "block");
	}); // end cvv_howto_link.click

	$("#cvv_howto_close").click(function(){
		$("#cvv_howto").css("display", "none");
	}); // end cvv_howto_close.click

} // End of cvvHooks()

/**
* Set up a hook to set the sumbit form item when the submit button is clicked.
*   Since the value of the button is translated we need the correct value.
*/
jQuery.fn.secrets.prefHook = function() {
    
	$(function(){
		//
		//submit form
		//
		$("#prefForm").submit(function(){
			$("#submit").val("save");
			return true;
		});// end submit
		
	});// end function
    
}// End of prefHook()

/**
* Set up our hook for the hidden password that's displayed to the user.
*/
jQuery.fn.secrets.passwordHiddenHook = function() {

	var orig_color = $("#password-hidden").css("background-color");

	//
	// Unhide the password.
	//
	$("#password-hidden").mouseover(function() {
		$(this).css("background-color", "white");
	});

	//
	// Hide it again.
	//
	$("#password-hidden").mouseout(function() {
		$(this).css("background-color", orig_color);
	});

} // End of jQuery.fn.secrets.passwordHiddenHook()

/**
* Set up code for adding campaign for an admin
*/
jQuery.fn.secrets.campaignAddFormAdmin = function(){
	$("#campaign_add_admin").click(function(){
		$.post(	"campaigns.php", 
				{
				id: $("#campaign_user_id").val(),
				name: $("#campaign_new").val(),
				task: "create",
				return_type: "json"
				}, 
				function(data){
					$("#campaigns_content").html(data);
					$("#campaign_new").val("");
				}, 
				"json"
		); // end post
	});// end campaign_add.click 

}// end jQuery.fn.secrets.campaignAddFormAdmin


/**
* Set up sorting/editing files for for campaigns
*/
jQuery.fn.secrets.campainList = function(){
	$("#campaigns_domain").click(function(event){
		var $target = $(event.target);

		if($target.attr('id') == 'add'){
		    $.post(	"campaigns.php", 
			    {
			    id: $("#campaign_user_id").val(),
			    name: $("#campaign_new").val(),
			    task: "create",
			    return_type: "json"
			    }, 
			    function(data){
				    if (data.campaigns.addform_html.length > 0) {
					    $("#campaign_add_domain").html(data.campaigns.addform_html);
				    }
				    $("#campaigns_message").html(data.campaigns.campaigns_message);
				    $("#campaign_new").val("");
				    $("#campaigns_content").html(data.campaigns.campaign_html);
			    }, 
			    "json"
		    ); // end post
		} // end update if/then
		
		else if($target.attr('task') == 'update'){
			$("#campaign_add").fadeOut();
			$.post(	"campaigns.php", 
					{
					id: $("#campaign_user_id").val(),
					selected_id: $target.attr('value'),
					task: "update",
					return_type: "json"
					}, 
					function(data){
						$("#campaigns_content").html(data);
					}, 
					"json"
			); // end post
		} // end update if/then
		
		else if($target.attr('task') == 'cancel'){
			$.post(	"campaigns.php", 
					{
					id: $("#campaign_user_id").val(),
					task: "list",
					return_type: "json"
					}, 
					function(data){
						$("#campaigns_content").html(data);
						$("#campaign_add").fadeIn();
					}, 
					"json"
			); // end post
		} // end cancel if/then
		
		else if($target.attr('task') == 'save'){
			$.post(	"campaigns.php", 
					{
					id: $target.attr('value'),
					user_id: $("#campaign_user_id").val(),
					name: $("#campaign_name").val(),
					task: "update",
					submit: "save",
					return_type: "json"
					}, 
					function(data){
						$("#campaigns_content").html(data);
						$("#campaign_add").fadeIn();
					}, 
					"json"
			); // end post
		} // end save if/then
		
		else if($target.attr('task') == 'sort'){
			var id = $target.attr('value');
			var direction_id = "#" + id + "_direction"
			var direction = $(direction_id).val();
			
			$.post(	"campaigns.php", 
					{
					id: $("#campaign_user_id").val(),
					task: "sort",
					order_by: id,
					direction: direction,
					return_type: "json"
					}, 
					function(data){
						$("#campaigns_content").html(data);
						
						direction = (direction == "DESC") ? "ASC" : "DESC";
						$(direction_id).val(direction);
						
						$("#campaign_add").fadeIn();
					}, 
					"json"
			); // end post
		} // end sort if/then
		
		
	}); // end a.click
	
}// end jQuery.fn.secrets.campainList

/**
* Set up a hook to submit agent_list data.
* 
*/
jQuery.fn.secrets.agent_listHook = function(){
	
	$("#agent").click(function(event){
		var $target = $(event.target);
	    var id = $target.attr('value');
	    
		if($target.attr('task') == 'filter'){
			var direction_id = "#" + id + "_direction"
			var direction = $(direction_id).val();
						
			$.post(	"index.php", 
					{
					task: "filter",
					order_by: id,
					direction: direction,
					return_type: "json"
					}, 
					function(data){
						$("#agent").html(data);
						direction = (direction == "DESC") ? "ASC" : "DESC";
						$(direction_id).val(direction);
						if(id == "last"){
							$("#first_direction").val(direction);
						}else if(id == "first"){
							$("#last_direction").val(direction);
						}
					}, 
					"json"
			); // end post
		} // end filter if/then
		
		else if($target.attr('task') == 'update'){
			location.replace("index.php?task=update&id=" + id);
		
		} // end filter if/then
		
	}); // end a.click
	
}// End of jQuery.fn.secrets.agent_form.Hook()


/**
* Set up a hook to submit agent_form data.
* 
*/
jQuery.fn.secrets.agent_formHook = function(){
	//
	//submit form
	//
	$("#agent_form").submit(function(){
	    var message = unescape($("#message").val());
	    message = message.replace(/\+/g, " ");	
	
		if( confirm(message)){
			$("#submit").val("save");
			return true;
		}else{
			return false;
		}
	});// end submit

	//
	//Lock account
	//
	$("#admin_agent #lock").click(function(){
	    var message = "You have chosed to either lock/unlock this agent's account. " +
	            "Do you want to proceed?\n\n" +
	            "Click 'Yes' to continue, and 'Cancel' to cancel.";
	 
	  	if(confirm(message)){
    	    var url = $("#admin_agent #lock").attr("value");
    	    location.replace(url);
    	}
   });// end lock account
   
   
   //
   // country code
   //   
   $("#country_code").change(function(){
        var $country = $("#country_code :selected").text();
        $("#country").val($country);
   
   });  // end country code

	//
	//Change Business type
	//
	$("#agent #is_company").change(function(){
	
	    //
	    // clear any potential error classes
	    //
        $("#ssn_ein_td").attr("class", "");
        $("#company_name_td").attr("class", "");
        
        if($("#is_company").val() == 0){
            //
            //TURN OFF
            //
            $("#company_name_div").css("display", "none");
            $("#company_name").css("display", "none");
            $("#ein").css("display", "none");
            //
            //TURN ON
            //
            $("#ssn_ein_title").html("SSN");
            $("#ssn").css("display", "block");

        }else{
            //
            //TURN OFF
            //
            $("#ssn").css("display", "none");
            //
            //TURN ON
            //
            $("#ssn_ein_title").html("EIN");
            $("#company_name_div").css("display", "block");
            $("#company_name").css("display", "block");
            $("#ein").css("display", "block");

        }
	  });// end lock account
	
}// End of jQuery.fn.secrets.agent_form.Hook()

/**
* Set up a hook to submit staff_form data.
* 
*/
jQuery.fn.secrets.staff_formHook = function(){
	//
	//submit form
	//
	$("#staff_form").submit(function(){
	    var message = unescape($("#message").val());
	    message = message.replace(/\+/g, " ");	
	
		if( confirm(message)){
			$("#submit").val("save");
			return true;
		}else{
			return false;
		}
	});// end submit
	
}// End of jQuery.fn.secrets.staff_form.Hook()


/**
* Set up a hook to open the login modal
*
*/
jQuery.fn.secrets.login_modal_buttonHook = function() {
	$("#login_modal_button").click(function(){
		var url = "login.php?modal=true";
		$(".jqmWindow").jqm({ajax: url});
		$(".jqmWindow").jqmShow(); 
	}); // end login click

} // end login_modal_buttonHook
	
	
/**
* Set up a hook to submit login data.
* 
*/
jQuery.fn.secrets.loginHook = function(){
	//
	//submit form
	//
	$("#login").submit(function(){
        $("#submit").val("save");
       return true;
	});// end submit
	
}// End of jQuery.fn.secrets.login.Hook()


/**
* Set up a hook for when an item radio button is clicked.
*/
jQuery.fn.secrets.itemHook = function() {

	var update_total = function() {

		//
		// Find the price of the selected element.
		//
		var element = $("input.item_radio:checked").parent()
			.find(".item_price");
		var total = element.text();

		//
		// This is some crazy code to add in a decimal point with 2 places
		// of precision, since we don't have printf() for Javascript.
		//
		var total_length = total.length;
		//
		// Turn the number (really a string) into a floating point and
		// multiply by 100 and then round so we don't have any decimal
		// points left.
		//
		total_num = parseFloat(total);
		total_num = Math.round(total_num * 100);
		//
		// Turn the number back into a string and insert a decimal 
		// point 2 characters from the end.
		//
		total_string = String(total_num);
		total_string_len = total_string.length;
		index = total_string_len - 2;
		total_string_format = total_string.substr(0, index) 
			+ "." + total_string.substr(index, 2);

		$(".item_total").text("$" + total_string_format + " USD");

	}

	//
	// Update the total to pa Update the total to payy
	//
	update_total();
	$(".item_radio").click(function() {
		update_total();
	});

} // End of jQuery.fn.secrets.itemHook()


/**
* Set up hooks for our Royalties form.
*/
jQuery.fn.secrets.royalties = function() {

	//
	// Focus on our first input element.
	//
	var element = $("#royalties").find("input[name='num_users']");
	element.focus();

} // End of jQuery.fn.secrets.royalties()


/**
* This is a plugin within a plugin.  It is responsible for displaying
* a modal to the user, that allows them to click "OK" or "Cancel".
*/
jQuery.fn.secrets.modal = function() {} // End of modal()


/**
* Display the modal over top of the current page.
*
* @param function message The message to display in the modal.
*
* @param function callbackOkay The callback to run when the user clicks ok.
*
* @param function callbackCancal The callback to run when the user clicks cancel.
*
*/
jQuery.fn.secrets.modal.popup = function(message, callbackOkay, callbackCancel) {

	var url = "confirm_modal.php";
	$(".jqmWindow").jqm({"ajax": url, "onShow": jQuery.fn.secrets.modal.onShow});
	$(".jqmWindow").jqmShow();

	jQuery.fn.secrets.modal.message = message;
	jQuery.fn.secrets.modal.callbackOnOkayCore = callbackOkay;
	jQuery.fn.secrets.modal.callbackOnCancelCore = callbackCancel;

} // End of popup()


/**
* The callback to run when jqModal shows the window.
*
* @param array hash An array of different elements that jqModal provides.
*/
jQuery.fn.secrets.modal.onShow = function(hash) {

	//
	// This function will be set to hook a click event on the "Okay" button
	// from the confirm_modal.php file that's included.
	// This is defined here, since we need the hash variable to be in 
	// the function's scope.
	//
	jQuery.fn.secrets.modal.callbackOnOkayFromTemplate = function() {
		//
		// Remove the "window" and overlay
		//
		hash.w.remove();
		hash.o.remove();
		//
		// Execute our handler after the modal is gone
		//
		jQuery.fn.secrets.modal.callbackOnOkayCore();
	}

	//
	// This function will be set to hook a click event on the "Cancel" button
	// from the confirm_modal.php file that's included.
	// This is defined here, since we need the hash variable to be in 
	// the function's scope.
	//
	jQuery.fn.secrets.modal.callbackOnCancelFromTemplate = function() {
		//
		// Remove the "window" and overlay
		//
		hash.w.remove();
		hash.o.remove();
		//
		// Execute our handler after the modal is gone
		//
		jQuery.fn.secrets.modal.callbackOnCancelCore();
		};

	//
	// Show the current modal.
	//
	hash.w.show();

} // End of onOpen()


/**
* Default "okay" handler.  This can (and should!) be overwritten.
*/
jQuery.fn.secrets.modal.callbackOnOkayCore = function() {
	alert("Default OnOkay handler.  Please replace me!");
}


/**
* Default "cancel" handler.  This can (and should!) be overwritten.
*/
jQuery.fn.secrets.modal.callbackOnCancelCore = function() {
	alert("Default OkCancel handler.  Please replace me!");
}


