$.fn.search = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};


$(function(){															// On document-ready
	$('a').focus(function() { this.blur(); });							// Blur on focus
	$('input[type*=submit]').focus(function() { this.blur(); });		// Blur on focus
	$('form.ajaxform').ajaxSubmit();									// Ajaxify forms
	$('form.prettyform input[type*=radio]').css('border','none');		// Pretty forms
	$('form.prettyform input[type*=checkbox]').css('border','none');	// Pretty forms
	if($.browser.mozilla) { prettyform(); }								// Pretty forms for Firefox
	$("div.formMessage").html($("div.formMessage").html() + "<div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formMessage').fadeOut('normal');\">X</a></div>");
	$('#company_name').change(function(){companycheck();});
	$('#company_blurb').keyup(function(){limitChars('company_blurb', 350);});
	//$('label.required').append(' <em>*</em>'); 
	if( $("table.sort").length ){
		$("table.sort").tablesorter({dateFormat: 'uk'}); 
	}
	if( $("#moreOptionsLink").length ){
		$("#moreOptionsLink").click(function(){
			$('#moreSearchOptions').toggle(400, function(){ 
				if( $("#moreSearchOptions:visible").length ){
					$("#moreOptionsLink").text('Less options');
				} else { $("#moreOptionsLink").text('More options'); }
			} );
		
		});
	}
	if( $("#moreSearchOptions:visible").length ){ $("#moreOptionsLink").text('Less options'); }
	//$('#dropdownNav').show();
	if( $("#dropdownIcon").length ){
		$("#dropdownIcon").click(function(){
			$('#dropdownNav').toggle();
			$('#dropdownNav').parent('li').toggleClass('subActive');
			$(this).toggleClass('selected');
		});
	}
	
	$("#searchInput").search();
	$("#inputSearch").search();
	
	$("a.downloadcheck").click(function(){
		if ($(this).siblings('img').is(":hidden")) {
			 $(this).siblings('img').show();
		}
	});
	
	$("table.pricing tbody tr").find("td:eq(1),td:eq(2),td:eq(3)").addClass('center');
	
});

function limitChars(textid, limit) {
	var text = $('#'+textid).val(); 
	var textlength = text.length;

	if(textlength > limit) {
		$('#'+textid).val(text.substr(0,limit));
		return false;
	} else {
		return true;
	}
}

function companycheck(){
	$.get('/signup/companycheck', {company_name: $('#company_name').val()},
		function(data){
			$('#matches').remove();
			if($(data).find('matchcount').text()*1 >0){
				appendstr = '<div id="matches" class="matches">';
				appendstr = appendstr+'<h2>Warning:</h2> <p>The company name you entered is very similar to a company that has already been entered.</p>';
				appendstr = appendstr+'<p>If any of these companies are yours please contact the person that signed up and get them to add you as an idividual contact.</p>';
				appendstr = appendstr+'<p>If these are not your company please continue to complete the signup.</p>';
				appendstr = appendstr+'<table class="greyblock" width="100%" cellspacing="2" cellpadding="0">'
					    +'<thead>'
					      +'<tr>'
					          +'<th width="*">Company</th>'
					          +'<th width="10%">Phone</th>'
					          +'<th width="20%">Email</th>'
					      +'</tr>'
					    +'</thead>'
					    +'<tbody>';
				$(data).find('match').each(function(){
					appendstr = appendstr+'<tr><td>'+$(this).find('name').text()+'</td>';
					appendstr = appendstr+'<td>'+$(this).find('phone').text()+'</td>';
					appendstr = appendstr+'<td>'+$(this).find('email').text()+'</td></tr>';
				});
				appendstr = appendstr+'</tbody></table>';
				appendstr = appendstr+'</div>';
				
				$('#name_matches').append(appendstr);
				
			}
		}
	);
}

function prettyform(){
  // Hide forms
  $( 'form.prettyform' ).hide().end();
  
  // Processing
  $( 'form.prettyform' ).find( 'li label' ).not( '.noprettyform' ).each( function( i ){
    var labelContent = this.innerHTML;
    var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
    var labelSpan = document.createElement( 'span' );
        labelSpan.style.display = 'block';
        labelSpan.style.width = labelWidth;
        labelSpan.innerHTML = labelContent;
    this.style.display = '-moz-inline-box';
    this.innerHTML = '';
    this.appendChild( labelSpan );
  } ).end();
  
  // Show forms
  $( 'form.prettyform' ).show().end();
}

function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	   num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
			  num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function securePass(passField, secureField)
{
	$('#'+secureField).val( md5( $('#'+passField).val() ) );
	$('#login-password').val('');
}

function alterContact(uid) {
	$("body").addClass("curWait");
	
	if( $('#preferred-'+uid).attr('checked') == true )
		task = 'assoc';
	else
		task = 'unassoc';
	$.post("/mycontacts/update?task=" + task + "&id=" + uid + "&call=ajax", function(xml){
		$("body").removeClass("curWait");
		strError = "Unable to update contact list. Please try again later.";
		oFocus = null;
		$("AjaxResponse", xml).each(function() {
			
			strError = this.getAttribute("error");
		});
		if (strError.length == 0) {
			$("div.formMessage").html("<div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formMessage').fadeOut('normal');\">X</a></div>Your preferred contacts list was updated successfully!").fadeIn("normal");
		} else {
			//alert("The following errors were encountered:\n" + strError);
			$("div.formMessage").hide();
			$("div.formErrors").html("<h5>Error<\/h5><div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formErrors').fadeOut('normal');\">X</a></div><ul class=\"sm\">" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
		}
	});
}
 
$.fn.ajaxSubmit = function(e) {		
	/* Change a form's submission type to ajax */
	this.submit(function(){
						 
	if( $('#my_account-form') )
		selectCategory();
		
	var params = {};
	$(this)
	.find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea")
	.filter(":enabled")
	.each(function() {
	  params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
	});
	$("body").addClass("curWait");
	
		$.post(this.getAttribute("action") + "&call=ajax", params, function(xml){
			$("body").removeClass("curWait");
			strError = "Unable to submit form. Please try again later.";
			oFocus = null;
			$("AjaxResponse", xml).each(function() {
				strRedirect = this.getAttribute("redirecturl");
				strError = this.getAttribute("error");
				oFocus = this.getAttribute("focus");
			});
			
			if (strError.length == 0) {
				window.location = strRedirect;
			} else {
				$("div.formMessage").hide();
				$("div.formErrors").html("<h5>Error<\/h5><div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formErrors').fadeOut('normal');\">X</a></div><ul class=\"sm\">" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
				if (oFocus) $("#" + oFocus).get(0).focus();
			}
		});
		return false;
	});
	
	return this;
}

// Trade Categories select lists

function retrieveCat2(first_cat, second_cat, third_cat){
	if( isNaN($('#'+first_cat).val()) && $('#'+first_cat).val() <= 0 ){
		//window.location = 'http://dev.interspeed.co.nz/onlyonelink/signup.php';
		window.location = '/signup';
		return false;
	}
	
	//$.post('/onlyonelink/library/category.php', { selector: second_cat, cat1_id: $('#'+first_cat).val(), cat2_id: $('#'+second_cat).val(), ajax: "true" }, function(xml){
	$.post('/index/category', { selector: second_cat, cat1_id: $('#'+first_cat).val(), cat2_id: $('#'+second_cat).val(), ajax: "true" }, function(xml){
		var cat_options = '<option value="null">Select category</option>';
	
		$(second_cat,xml).each( function(i){
			cat_options += '<option value="' + $(this).attr('id') + '">' + $(this).text() + '</option>';
		});
		
		$("#"+second_cat).html(cat_options);
		$('#'+second_cat+' option:first').attr('selected', 'selected');

		$("#"+third_cat).html('<option value="null">Select category</option>');
		$('#'+third_cat+' option:first').attr('selected', 'selected');
	});
}

function retrieveCat3(second_cat, third_cat){
	if( isNaN($('#'+second_cat).val()) && $('#'+second_cat).val() <= 0 ){
		//window.location = 'http://dev.interspeed.co.nz/onlyonelink/signup.php';
		window.location = '/signup';
		return false;
	}
	//$.post('/onlyonelink/library/category.php', { selector: third_cat, cat2_id: $('#'+second_cat).val(), cat3_id: $('#'+third_cat).val(), ajax: "true" }, function(xml){
	$.post('/index/category', { selector: third_cat, cat2_id: $('#'+second_cat).val(), cat3_id: $('#'+third_cat).val(), ajax: "true" }, function(xml){
		var cat_options = '<option value="null">Select category</option>';	
			
		$(third_cat,xml).each( function(i){
			cat_options += '<option value="' + $(this).attr('id') + '">' + $(this).text() + '</option>';
		});
		
		$("#"+third_cat).html(cat_options);
		$('#'+third_cat+' option:first').attr('selected', 'selected');
	});
}

function addSelectedCategory(first_cat, second_cat, third_cat, selected_cat,prefix) {
	var categories_selected = $("#"+selected_cat).html();
	var new_cat = '';
	
	if ($('#'+third_cat).val() != 'null') {
	//add single category
		if( $('#'+selected_cat).children("[value=" + $('#'+third_cat).children("[selected]").val() + "]").val() ){
			alert('You\'ve already added that item to the list!');
		} else {
			new_cat = '<option value="' + $('#'+third_cat).val() + '">' + $('#'+first_cat+' option:selected').text() + " &gt; " + $('#'+second_cat+' option:selected').text() + " &gt; " + $('#'+third_cat+' option:selected').text() + '</option>';
		}
		categories_selected += new_cat;
		$("#"+selected_cat).append(new_cat);
	//	$("#"+selected_cat).html(categories_selected);
	} else if ($('#'+second_cat).val() != 'null') {
	//add all categories which are children of the second list's selected item - all siblings 
	//$.post('/onlyonelink/library/category.php', { selector: third_cat, cat2_id: $('#'+second_cat).val(), cat3_id: $('#'+third_cat).val(), ajax: "true" }, function(xml){
		$.post('/index/category', { selector: third_cat, cat2_id: $('#'+second_cat).val(), cat3_id: $('#'+third_cat).val(), ajax: "true" }, function(xml){
			var categories_selected = $("#"+selected_cat).html();
			var new_cat = '';
		
			$(third_cat,xml).each( function(i){
							//			 alert($(this).attr('id'));
				if( $('#'+selected_cat).children("[value=" + $(this).attr('id') + "]").val() ){
					// item already present in the list
				}
				else {
					new_cat = new_cat + '<option value="' + $(this).attr('id') + '">' + $('#'+first_cat+' option:selected').text() + " &gt; " + $('#'+second_cat+' option:selected').text() + " &gt; " + $(this).text() + '</option>';
				}
			});

			categories_selected += new_cat;
			$("#"+selected_cat).append(new_cat);
		//	$("#"+selected_cat).html(categories_selected);
		});
	} else if ($('#'+first_cat).val() != 'null') { 
	//add all categories which are children of the first list's selected item - all siblings and all parent's siblings' children
	//$.post('/onlyonelink/library/category.php', { selector: prefix+"cat_grandparent", cat1_id: $('#'+first_cat).val(), ajax: "true" }, function(xml){
		$.post('/index/category', { selector: prefix+"cat_grandparent", cat1_id: $('#'+first_cat).val(), ajax: "true" }, function(xml){
			var categories_selected = $("#"+selected_cat).html();
			var new_cat = '';
		
			$(third_cat,xml).each( function(i){
				// alert($(this).attr('id'));
				if( $('#'+selected_cat).children("[value=" + $(this).attr('id') + "]").val() ){
					// item already present in the list
				}
				else {
					new_cat = new_cat + '<option value="' + $(this).attr('id') + '">' + $('#'+first_cat+' option:selected').text() + " &gt; " + $(this).attr('parent_text') + " &gt; " + $(this).text() + '</option>';
				}
			});

			categories_selected += new_cat;
			$("#"+selected_cat).append(new_cat);
		//	$("#"+selected_cat).html(categories_selected);
		});
	}
	
}

function removeCat(allCats, selected_cat) {
	if (allCats == 'true') {
		$("#"+selected_cat).html("");
	}
	else {
		// Validate
		if( !$('#'+selected_cat).children("[selected]").val() ){
			alert('You must select a category!');
			return false
		}
		
		// Remove the selected item
		$('#'+selected_cat).children("[selected]").remove();
	}
	return true;
}


function addListElement(source_list, destination_list){
	// Validate
	if( !$('#'+source_list).children("[selected]").val() ){
		alert('You must select an item to add!');
		return false
	}
	
	// Check this options isn't already in the list
	if( $('#'+destination_list).children("[value=" + $('#'+source_list).children("[selected]").val() + "]").val() ){
		alert('You\'ve already added that item to the list!');
		return false;	
	}
	
	// Compose the new option
	newoption = "<option value=\"" + $('#'+source_list).children("[selected]").val() + "\">" + $('#'+source_list).children("[selected]").text() + "</option>";

	// Append the new option
	
	$('#'+destination_list).append(newoption);
	
	return true;
}

function removeListElement(destination_list){
	// Validate
	if( !$('#'+destination_list).children("[selected]").val() ){
		alert('You must select an item to remove!');
		return false
	}
	
	// Remove the selected item
	$('#'+destination_list).children("[selected]").remove();
	
	return true;
	
}

function selectCategory(){
//	$('#categories_selected').attr('multiple', true);
//	$('#categories_selected').attr('name', $('#categories_selected').attr('name') + "[]");
	$('#categories_selected').children().each(function(i){
		$('#my_account-form').append("<input type=\"hidden\" name=\"categories[" + $(this).val() + "]\" value=\"" + $(this).text() + "\">");
	});
	return true;
}

function selectUserCategory(){
	$('#categories_selected').children().each(function(i){
		$('#user-form').append("<input type=\"hidden\" name=\"categories[" + $(this).val() + "]\" value=\"" + $(this).val() + "\">");
	});
	return true;
}

function selectJobsCategory(){
	$('#categories_selected').children().each(function(i){
		$('#my_jobs-form').append("<input type=\"hidden\" name=\"categories[" + $(this).val() + "]\" value=\"" + $(this).text() + "\">");
	});
	return true;
}
function selectJobsPrefCompany(){
	$('#pref_company').children().each(function(i){
		$('#my_jobs-form').append("<input type=\"hidden\" name=\"preferred_contractors[" + $(this).val() + "]\" value=\"" + $(this).text() + "\">");
	});
	return true;
}
function selectJobsNomCompany(){
	$('#nom_company').children().each(function(i){
		$('#my_jobs-form').append("<input type=\"hidden\" name=\"nominated_contractors[" + $(this).val() + "]\" value=\"" + $(this).text() + "\">");
	});
	return true;
}
function selectNLocation(){
	$('#n_sel_location').children().each(function(i){
		$('#my_filters-form').append("<input type=\"hidden\" name=\"locations_sel[" + $(this).val() + "]\" value=\"" + $(this).val() + "\">");
	});
	return true;
}
function selectNCompany(){
	$('#n_sel_company').children().each(function(i){
		$('#my_filters-form').append("<input type=\"hidden\" name=\"companies_sel[" + $(this).val() + "]\" value=\"" + $(this).val() + "\">");
	});
	return true;
}
function selectNCategory(){
	$('#n_categories_selected').children().each(function(i){
		$('#my_filters-form').append("<input type=\"hidden\" name=\"categories_sel[" + $(this).val() + "]\" value=\"" + $(this).val() + "\">");
	});
	return true;
}
function selectNProjectType(){
	$('#n_sel_project_type').children().each(function(i){
		$('#my_filters-form').append("<input type=\"hidden\" name=\"project_types_sel[" + $(this).val() + "]\" value=\"" + $(this).val() + "\">");
	});
	return true;
}

function submitJobsForm() {
	selectJobsCategory();
	selectJobsPrefCompany();
	selectJobsNomCompany();
//	document.getElementById("my_jobs-form").action = "/myjobs/edit";
	document.getElementById("my_jobs-form").submit();
}

function submitAccountForm() {
	selectCategory();
	document.getElementById("my_account-form").action = "/myaccount";
	document.getElementById("my_account-form").submit();
}

function submitFiltersForm() {
	selectNLocation();
	selectNCompany();
	selectNCategory();
	selectNProjectType();
	document.getElementById("my_filters-form").action = "/myfilters?option=update";
	document.getElementById("my_filters-form").submit();
}

function submitSignupForm() {
	selectUserCategory();
	document.getElementById("user-form").action = "/signup";
	document.getElementById("user-form").submit();
}

function submitTendersForm(btn_type) {
	if (btn_type == 'del')	{	option = "del";		}
	else					{	option = "update";	}
	selectJobsCategory();
	document.getElementById("my_tenders-form").action = "/mytenders?option="+option;
	document.getElementById("my_tenders-form").submit();
}

$(document).ready(
    function() {
        $('#search_provenceid').chainSelect('#search_cityid','/signup/getcities');
        $('#search_provenceid');
        
        $('#p_company_provenceid').chainSelect('#p_company_cityid','/signup/getcities');
        
        //{
        //    before: function(target) { window.temp_cpid = $(target).val(); },
        //    after:  function(target) { $(target).val(window.temp_cpid); }
        //}
        
        $('#company_provenceid').chainSelect('#company_cityid','/signup/getcities');
        //$('#company_provenceid').change();
    }
);

$(function(){ $('#browse').change(function(){ $('#output').html('<span>Filename:</span> ' + $(this).val()); }); });
