//	Site-wide Javascript functions

//	Note: If you plan to use jQuery, it must be wrappered inside an onReady function declaration

jq(document).ready(function() {
	//	jQuery code goes here
	// Hide the button on the programme selector
	jq("#programme_selector_button").css({display: 'none'});
	// Auto submit form on change
	jq("#programme_selector").bind("change", function(e) {
		if (jq(this).val() > 0) {
			jq(this).parent('form').get(0).submit();
		}
	});
	
	//	Some CSS corrections
	jq("input[type=submit]").addClass('button');
	jq("input[type=checkbox]").css({background: "#fff", border: "0px"});

	//	Tooltip support

	//	This function gets the tooltip to track the movement of the mouse
	jq.fn.tooltipmove = function(e) {
//		var xMouseSpace = 15;
//		var tipWidth = 250;
//		var windowWidth = jq(window).width();
//		var compareWidth = e.pageX + xMouseSpace + tipWidth + 20; // 20 - counteracts addition of scrollbar
//
//		if (compareWidth > windowWidth) {
//			jq("#helptexthover").css("left",  xMouseSpace - tipWidth);
//		    jq("#helptexthover").css("top", e.pageY + 20);
//		} else {
//		    jq("#helptexthover").css("left", xMouseSpace);
//		    jq("#helptexthover").css("top", e.pageY + 20);
//		}
	};


	//	These set up the display and tracking for all the elements that have help text
	jq("*[help_text]").bind('mouseover', function(e) {
		pos = jq(this).offset();
		jq("#helptexthover").css("top", pos.top + jq(this).height() + 5);
		jq("#helptexthover").css("left", pos.left +250);
        jq("#helptexthover").html(jq(this).attr('help_text')).show();
        //jq(this).addClass("hasFocus");
        //jq("#helptexthover").html(jq(this).attr('help_text')).show();
	});
	jq("*[help_text]").bind('mouseout', function() {
		if (jq(this).hasClass("hasFocus")) {
		//moving focus was causing problems with selects
		//			jq(this).focus();
		} else {
			jq('#helptexthover').hide();
		}
	});
	jq("*[help_text]").bind('mousemove', function(e) {
	    jq.fn.tooltipmove(e);
	});
	jq("*[help_text]").bind('focus', function(e) {
		//	position under the field we're providing help for
		pos = jq(this).offset();
		jq("#helptexthover").css("top", pos.top + jq(this).height() + 5);
		jq("#helptexthover").css("left", pos.left +250);
        jq("#helptexthover").html(jq(this).attr('help_text')).show();
        jq(this).addClass("hasFocus");
	});
	jq("*[help_text]").bind('blur', function(e) {
	    jq("#helptexthover").hide();
        jq(this).removeClass("hasFocus")
	});
	
	// This is to detect the changing of the Role Type dropdown on Admin Add User.
	// This will show/hide specific fields depending if they choose Adviser or not.
	var add_user_dropdown = jq('#add_user_role_id').eq(0);	
	if(add_user_dropdown.length > 0) {
		var changed = false;
		add_user_dropdown.change( function() {
			changed = true;
			if(add_user_dropdown.val() == 2) {
				jq("#field_tr_address1").fadeIn("slow");
				jq("#field_tr_address2").fadeIn("slow");
				jq("#field_tr_address3").fadeIn("slow");
				jq("#field_tr_towncity").fadeIn("slow");
				jq("#field_tr_county").fadeIn("slow");
				jq("#field_tr_postcode").fadeIn("slow");
				jq("#field_tr_phone").fadeIn("slow");
				jq("#field_tr_company_id").fadeIn("slow");
				jq("#field_tr_specialist").fadeIn("slow");
				jq("#field_tr_mobile").fadeIn("slow");				
				jq("#field_tr_company_name").fadeIn("slow");								
			} else {
				jq("#field_tr_address1").fadeOut("slow");
				jq("#field_tr_address2").fadeOut("slow");
				jq("#field_tr_address3").fadeOut("slow");
				jq("#field_tr_towncity").fadeOut("slow");
				jq("#field_tr_county").fadeOut("slow");
				jq("#field_tr_postcode").fadeOut("slow");
				jq("#field_tr_specialist").fadeOut("slow");
				jq("#field_tr_company_id").fadeOut("slow");
				jq("#field_tr_phone").fadeOut("slow");				
				jq("#field_tr_mobile").fadeOut("slow");				
				jq("#field_tr_company_name").fadeOut("slow");								
			}
		});		
		// we use changed as we don't want to run hide() on the fields every time we change the dropdown and its not == 2
		// therefore changed will only be true upon page load
		if(add_user_dropdown.val() != 2 && changed == false) {
			jq("#field_tr_address1").hide();
			jq("#field_tr_address2").hide();
			jq("#field_tr_address3").hide();
			jq("#field_tr_towncity").hide();
			jq("#field_tr_county").hide();
			jq("#field_tr_postcode").hide();
			jq("#field_tr_phone").hide();
			jq("#field_tr_mobile").hide();
			jq("#field_tr_company_id").hide();
			jq("#field_tr_company_name").hide();
			jq("#field_tr_specialist").hide();
		}
	}
	
	// This will show/hide the fields available for Editing depending if the user if
	// TBD - going to code this in the PHP for unset() instead.
	// @reason - security issues of HTML elements
	
	
	// This is for the Select all function of Batch Update
	var workitem_checkbox = jq('#workitem_checkbox_link').eq(0);	
	if(workitem_checkbox.length > 0) {
		jq('#workitem_checkbox_link').click(function() {
			jq("#workitem_checkbox_display").find("input[@type$='checkbox']").each(function(){
                //this.checked = (this.checked == true) ? false : true;
                this.checked = true;
            });
		});
	}
	
	// The following toggles the readonly attributes of the company address elements on the user registration page
	var company_dropdown_custom_checkbox = jq('#user_register_company_checkbox').eq(0);
	if(company_dropdown_custom_checkbox.length > 0) {
		
		// Check the default value of the checkbox, if its already checked then disable the readonly's
		if(company_dropdown_custom_checkbox.is(':checked')) {
			toggleAddressElements(false);				
		}
		// Hide the whole checkbox by default, until the dropdown.change() has been triggered.
		company_dropdown_custom_checkbox.click( function () {
			if(company_dropdown_custom_checkbox.is(':checked')) {
				toggleAddressElements(false)				
			} else {
				toggleAddressElements(true)							
			}
		});
	}	
	
	
	// The following code takes input from a company dropdown and makes an AJAX request to get JSON data from PHP
	// Taking the company address information and populating the relevant elements with address information.
	var company_dropdown = jq('#user_register_company_dropdown').eq(0);
	if(company_dropdown.length > 0) {
		// Get the default selected value (this is useful when errors are thrown and the previous
		// selected value is populated, rather than the default.
		var company_id = company_dropdown.val();
		if(company_id == 'new') {
			toggleElement('#field_tr_company_checkbox', 'hide');
			toggleElement('#field_tr_company_name', 'show');
			toggleAddressElements(false);
		} else if(company_id != '') {
			toggleElement('#field_tr_company_checkbox', 'show');
			toggleElement('#field_tr_company_name', 'hide');
		} else {
			toggleElement('#field_tr_company_checkbox', 'hide');
			toggleElement('#field_tr_company_name', 'hide');
		}
		
		company_dropdown.change( function() {
			// Update the company ID as we have a change.
			company_id = company_dropdown.val();
			// Here we show the checkbox row if 'please select' has not been chosen, if it has then we hide it again.
			if(company_id == '') {
				toggleElement('#field_tr_company_checkbox', 'hide');				
				toggleElement('#field_tr_company_name', 'hide');
			} else if(company_id == 'new') {
				toggleElement('#field_tr_company_checkbox', 'hide');
				toggleElement('#field_tr_company_name', 'show');
				toggleAddressElements(false);
			} else {
				jq('#user_register_company_name').val('');
				toggleElement('#field_tr_company_checkbox', 'show');
				toggleElement('#field_tr_company_name', 'hide');
				toggleAddressElements(true);				
			}
			// Regardless of the operation, if we change the dropdown, the value of the 'overwrite address' checkbox will go back to unchecked
			company_dropdown_custom_checkbox.removeAttr('checked');
			
			if(company_id != '' && company_id != 'new') {
				// Make the AJAX request and get JSON data back.
				jq.get(getBaseUrl('crwpmodel') + 'user/companyaddress/companyid/' + company_id + '/', function(res) {
					// This is actually the evalJSON() function of jQuery but it was doing random stuff and erroring so we just replicate its code here.
					var obj = eval("(" + res + ")");
					
					obj.company_address_1 = (obj.company_address_1 == null) ? '' : obj.company_address_1 ;
					obj.company_address_2 = (obj.company_address_2 == null) ? '' : obj.company_address_2 ;
					obj.company_address_3 = (obj.company_address_3 == null) ? '' : obj.company_address_3 ;
					obj.company_postcode = (obj.company_postcode == null) ? '' : obj.company_postcode;
					jq("#company_address_1").val(obj.company_address_1);
					jq("#company_address_2").val(obj.company_address_2);
					jq("#company_address_3").val(obj.company_address_3);
					jq("#company_postcode").val(obj.company_postcode);
				});	
			}			
		});
	}
	

	
});

	function toggleAddressElements(type) {
		if(type == false) {
			jq("#company_address_1").attr('readonly', false);
			jq("#company_address_2").attr('readonly', false);
			jq("#company_address_3").attr('readonly', false);
			jq("#company_postcode").attr('readonly', false);				
		} else {
			jq("#company_address_1").attr('readonly', true);
			jq("#company_address_2").attr('readonly', true);
			jq("#company_address_3").attr('readonly', true);
			jq("#company_postcode").attr('readonly', true);								
		}		
	}
	function toggleElement(elementName, type) {
		// Hide the whole row by default, until the dropdown.change() has been triggered.
		var element = jq(elementName).eq(0);
		if(element.length > 0) {
			if(type === undefined) {
				if(element.is(':hidden')) {			
					element.show();
				} else {
					element.hide();
				}
			} else {
				if(type == 'hide') {
					element.hide();
				} else {
					element.show();
				}
			}
		}		
	}
	/**
	  * This function is for the toggle show/hide of workItems from the Work Package Management Area
	  */
	/**
	  * @param wi_block_name The block name to ajax the contents of
	  * @param wp_id Work Package ID
	  * @param wi_id_list CSV List of all the Work Items To Show
	  */
	function toggleWorkItems(wi_block_name, wp_id, wi_id_list, user_type) {
		var tmpBlock = jq('#' + wi_block_name).eq(0);
		if(tmpBlock.length > 0) {
			var base_url = getBaseUrl();
			if(user_type == 'adviser') {
				var url = base_url + 'wp/adviser/ajaxworkitems/wpid/' + wp_id + '/ids/' + wi_id_list;
			} else {
				var url = base_url + 'wp/index/ajaxworkitems/wpid/' + wp_id + '/ids/' + wi_id_list;
			}
			var rowBlockName = '#tr_' + wi_block_name;
			var rowBlock = jq(rowBlockName).eq(0);
			if(rowBlock.length > 0) {
				if(rowBlock.is(':hidden')) {
					if(tmpBlock.html() == '&nbsp;') {
						jq(tmpBlock).load(url);
					}
					jq(rowBlock).fadeIn('slow');				
				} else {
					jq(rowBlock).fadeOut('slow');							
				}
			}
		}
	}
	
function getBaseUrl(app) {
	var host_name = document.location.hostname;
	if(host_name == 'ggdev.aeat.com' || host_name == 'ggdev') {
		var url = '/pmdev/';
	} else if(host_name == 'conwaste.aeastaging.co.uk') {
		var url = '/';
	} else {
		var url = '/';
	}
	if(app != '') {
		url += app + '/';
	}
	return url;
}