$(document).ready( 
	function()
	{
		for(var i=1; i< 9; i++)
		{
			$('#step-'+i).corner("10px");
		}
		$("#language_spoken_1").click(
			function()
			{
				$("#list_language").attr("disabled","disabled");
			}
		);
		
		$("#language_spoken_2").click(
			function()
			{
				$("#list_language").removeAttr("disabled");
			}
		);
		$('form').submit(function(){
		    // On submit disable its submit button
		    $('input[type=submit]', this).attr('disabled', 'disabled');
		});
		
		$('.credit-card-payment-border').corner("7px");
		$('.credit-card-payment').corner("7px");
		
		$('#dialog').dialog({autoOpen: false, width: 700, height: 600, buttons: {"   Close   ": function() {$(this).dialog("close");}}});
		$('#show_cv').dialog({autoOpen: false, width: 700, height: 600, buttons: {"   Close   ": function() {$(this).dialog("close");}}});
	}
);

function checkMaxLength(id, maxlimit,target)
{
	 var field = document.getElementById(id);
	 var display=document.getElementById(target);
	 if(field)
	 {
		 var len=field.value.length;
		 var temp=parseInt(maxlimit-len);
		 if(display)
		 {
			 document.getElementById(target).value=temp;
		 }
		 if (len > maxlimit)
		 {
			 field.value = field.value.substring(0, maxlimit);
		 }
	 }
 }
function loadTemplateCvOption (id, baseUrl, baseUrlOption, stylesheet)
{
	var script = '<link href="'+baseUrlOption+'/cvoptions_'+id+'.css?J='+stylesheet+'" rel="stylesheet" type="text/css" />';
	 //var script = '<link href="'+baseUrlOption+'/cvoptions_'+id+'.css rel="stylesheet" type="text/css" />';
	  script += '<script language="javascript" src="'+baseUrlOption+'/cvoptions_'+id+'.js?J='+stylesheet+'"></script>';
	 
	 $('#dialog').html(""); 
	 $('#dialog').dialog("close");
	 $.ajax({
	  type: "POST",
	  url : baseUrl+'/cvbuilder/ajaxloadcv',
	  data: "template_id=" + id,
	  success: function(html)
	  {
	   if (html != '1')
	   {
		   
	    $('#dialog').html(script+html);
	    $('#dialog').dialog('open');
	    $('#dialog').bgiframe();
	   } else {
	    alert ('This cv option does not exist!');
	   }
	  }
	 });
}
function loadDetailTemplateCvOption (disable_id,visible_id)
{
	$('#'+disable_id).hide();
	$('#'+visible_id).show();	
	$('#show_cv').dialog('open');
}
empl_status_1 = function(elementIndex)
{
	$("#date_leave_month-"+elementIndex).attr("disabled","disabled");
	$("#date_leave_day-"+elementIndex).attr("disabled","disabled");
	$("#date_leave_year-"+elementIndex).attr("disabled","disabled");
	$("#reason_leaving-"+elementIndex).attr("disabled","disabled");
}
empl_status_2 =function(elementIndex)
{
	$("#date_leave_month-"+elementIndex).removeAttr("disabled");
	$("#date_leave_day-"+elementIndex).removeAttr("disabled");
	$("#date_leave_year-"+elementIndex).removeAttr("disabled");
	$("#reason_leaving-"+elementIndex).removeAttr("disabled");
}

function loadCategories(countryId, baseURL)
{
    $("#classification_id").html("<option value=''>Loading...</option>");
    
    $.ajax({
        type: "POST",
        url : baseURL,
        data: "load=categories&country_id=" + countryId,
        success: function(html)
        {
            $("#classification_id").html(html);
            $('#classification_id :first').attr('selected', 'selected');
        }
    });
}
function changeCoutry(countryId, baseURL)
{
	var totalElement = baseURL.split('~~~~');
	if (totalElement[1])
	{
		baseURL = totalElement[1];
		totalElement = '-' + totalElement[0];
	} else {
		totalElement = '';
	}
	$("#region_id"+totalElement).html("<option value=''>Loading...</option>");
	if(countryId == '' || countryId == '-1')
	{
		$("#town_id"+totalElement).html("<option value=''>All</option>");
	}
	$("#ah_phone_01").html("<option value=''>Loading...</option>");
	
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=country&country_id=" + countryId,
		success: function(html)
		{
			$("#ah_phone_01").html("<option value='"+countryId+"'>"+countryId+"</option>");
			$("#region_id"+totalElement).html(html);
			$('#region_id'+totalElement+' :first').attr('selected', 'selected');
		}
	});
}

function changeAreaCode(country_id , control_id, baseURL)
{
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "country_id=" + country_id,
		success: function(html)
		{
			$("#"+control_id).html(html);
			$('#'+control_id+' :first').attr('selected', 'selected');
		}
	});
}

function changeRegion(regionId, baseURL)
{
	var totalElement = baseURL.split('~~~~');
	if (totalElement[1])
	{
		baseURL = totalElement[1];
		totalElement = '-' + totalElement[0];
	} else {
		totalElement = '';
	}
	var region_id = $('#region_id').val();
	
	$("#town_id"+totalElement).html("<option value=''>Loading...</option>");
	$("#contact_no_region_code"+totalElement).html("<option value=''>Loading...</option>");
	$("#phone_02").html("<option value=''>Loading...</option>");
	$("#ah_phone_02").html("<option value=''>Loading...</option>");
	
	//$('#phone_02').html('<option value='+region_id+'>'+region_id+'</option>');
	
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=region&region_id=" + regionId,
		success: function(html)
		{
			var arr = html.split("~~~");
			$("#town_id"+totalElement).html(arr[0]);
			$('#phone_02').html(arr[1]);
			$('#ah_phone_02').html(arr[1]);
			$("#contact_no_region_code"+totalElement).html(arr[1]);
			$("#list_region_id"+totalElement).html("<option value="+regionId+">"+regionId+"</option>");
			$('#list_region_id'+totalElement+' :first').attr('selected', 'selected');
		}
	});
}
function addAnother(baseURL)
{
	var element = parseInt($('#totalElement').val());
	var totalElement = element +1;
	var realTotal = parseInt($('#realTotal').val());
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=another&totalElement="+totalElement,
		success: function(html)
		{
			$("#recent-qualification").before('<div id ="line-box-'+element+'"><hr /><br /> </div>  '+html);
			$('#totalElement').val(totalElement);
			$('#realTotal').val(parseInt(realTotal)+1);//real value
			SetNumberStep7('totalElement');
			//showHideButtonRemove('button-remove', totalElement);
		}
	});
}

/*Sondt add to process show hide button remove*/
function showHideButtonRemove(prefix_id, totalElement)
{
	prefix_id = prefix_id+'-';
	var i=1;
	for(i= 1; i < totalElement; i++)
	{
		$('#'+prefix_id+i).show();
	}
	$('#'+prefix_id+totalElement).hide();
}

/*Sondt add to process remove box 
* @param baseURL
* @param inputId: this is input's id that contain primary key value.
* @param elementIndex: this is element that will delete in the future.
*/

function removeBox(baseURL, inputId, elementIndex)
{
	var id =  $('#'+inputId+ elementIndex).val();
	//removed-elements contain Id of removed element
	var removed = $('#removed-elements').val();
	var totalElement = $('#totalElement').val();
	totalElement = parseInt(totalElement);
	var realTotal = $('#realTotal').val();// store real value of element.
	var min = $('#min-element').val();// store min element.
	var i =1;
	if (realTotal == 1)
	{
		alert('The Box must exist at least one element!');
		return;
	}
	if (confirm('Do you want to delete this box '))
	{
		if(id != '0' && id != '' && id != null && id != 0 ){
			$.ajax({
				type: "POST",
				url : baseURL,
				data: "type=remove&id="+id,
				success: function(html)
				{
					//remove box
					$('#element-box-'+elementIndex).remove();
					//get element removed
					$('#removed-elements').val(removed+','+elementIndex);
					$('#realTotal').val(parseInt(realTotal)-1);//real value
					if(inputId =='rid-')//step 7
					{
						SetNumberStep7('totalElement');
					}
					removeLine(totalElement);	
				}
			});
		}else{
				//remove box
				$('#element-box-'+elementIndex).remove();
				//remove box
				$('#removed-elements').val(removed+','+elementIndex);
				$('#realTotal').val(parseInt(realTotal)-1);//real value
				if(inputId =='rid-')//step 7
				{
					SetNumberStep7('totalElement');
				}				
				removeLine(totalElement);			
		}	
	}
}
function removeLine(totalElement)
{
	var i=0;
	var k=0;
	// clear line
	for (i= 1; i <= totalElement; i++)
	{
		$('#line-box-'+i).html('');
	}
	var removedElement = $('#removed-elements').val();
	removedElement = removedElement.split(',');
	removedElement = removedElement.sort(sortNumber);
	
	k = 0;
	var rs = Array();
	for (i=1; i <= totalElement; i++)
	{
		if (!in_array(i, removedElement))
		{
			rs[k] = i;
			k++; 
		}
	}
	rs = rs.sort(sortNumber);
	if (k > 0)
	{
		for (i=0; i < k-1; i++)
		{
			$('#line-box-'+rs[i]).html('<hr /><br />');
		}
	}
}
function sortNumber(a,b)
{
	return a - b;
}
function in_array( what, where )
{
      var a=false;
      for(var i=0;i<where.length;i++)
      {
      	if(what == where[i])
      	{
      		a=true;
      		break;
      	}
      }
      return a;
}
function createSkillsInterests(type, total, book)
{
	var totalElements = parseInt($('#'+total).val())+1;
	var baseUrl = $('#baseUrl').val()
	if (book == 'book')
	{
		var html = '<div class="rightWrap2"><div class="rightLabel2 ts-formSubHeader">'+totalElements+'</div>'; 
		html += '<div><input type="text" class="inputText2" name="cid-'+type+'[]" id="cid-'+type+'-'+totalElements+'" /></div></div>';
	}
	else
	{
		var html = '<div id="box-'+type+'-'+totalElements+'" align="right" style="padding-top:5px;"><span id="num-'+type+'-'+totalElements+'"  class="step5-dot ts-cvAnswer">'+totalElements+'.</span>'; 
		html += '<input name="cid-'+type+'-'+totalElements+'" id="cid-'+type+'-'+totalElements+'" value="0" type="hidden" >';
	    html += '<input name="content-'+type+'-'+totalElements+'" id="content-'+type+'-'+totalElements+'" value="" type="text" class="long-input" style="width:320px; border: none;">';
		html += '<img onclick="javascript:removeText45(\'/Cvbuilder/create+cv+step+4\', \''+type+'\', \''+total+'\', \''+totalElements+'\');" src="/theme/images/box-delete-ico.gif" style="cursor: pointer;"> </div>';
	}
	$('#'+type+'-skills-row').before(html);
	$('#'+total).val(totalElements);
	SetNumberText(type, total);
}
/*
* @method: removeText45: remove textbox in step 4 & 5
* @param: baseURL, idRemoved(this is id of div), idGetKey(get primary key of website_cv_skills_interests_tmp table)
*
*/
function removeText45(baseURL, type, total_name, elementIndex)
{
	//$('#box-'+type+'-'+elementIndex);
	var id =  $('#cid-' + type + '-'+ elementIndex).val();// box id.
	var removed_arr = $('#removed-'+type).val();
	/*checking for case: at least has one element.*/
	var count =0;
	var itotal = $('#'+total_name).val();
	for(i = 1; i <= itotal; i++){
		if($('#box-'+type+'-'+i).html() != null){
			count++;
		}
	}
	if (count == 1){
		alert('The Text must exist at least one element!');
		return;
	}
	if (confirm('Do you want to delete this text box'))
	{
		if(id != '0' && id != '' && id != null && id != 0 ){
			$.ajax({
				type: "POST",
				url : baseURL,
				data: "type=remove&id="+id,
				success: function(html)
				{
					$('#box-'+type+'-'+elementIndex).remove();
					SetNumberText(type, total_name);
					$('#removed-'+type).val(removed_arr+','+elementIndex);
				}
			});
		}else{
				$('#box-'+type+'-'+elementIndex).remove();
				SetNumberText(type, total_name);
				$('#removed-'+type).val(removed_arr+','+elementIndex);
		}	
	}
}
function SetNumberText(type, total_name)
{
	var itotal = $('#'+total_name).val();
	var index = 0;
	for(i = 1; i <= itotal; i++){
		
		if($('#box-'+type+'-'+i).html() != null){
			index++;
			$('#num-'+type+'-'+i).html(index+'.');
		}
	}
}
function SetNumberStep7(total_name)
{
	var itotal = $('#'+total_name).val();
	var index = 0;
	for(i = 1; i <= itotal; i++){
		
		if($('#element-box-'+i).html() != null){
			index++;
			$('#num-rid-'+i).html(index);
		}
	}
}

function submitFormControl(type)
{
	if (type == 'upload')
	{
		baseUrlAction = $('#action_upload').val()+'?type=upload';
	} else {
		baseUrlAction = $('#action_upload').val();
	}
	document.getElementById('myForm').action = baseUrlAction;
	if (type == 'upload')
	{
	   // Setup attributes for form control
	   $('#upload-form-control').hide();
	   $('#upload-progress').fadeIn("slow");
	   
	   var image_file = $('#uploadFile').val();
	   if (jQuery.trim(image_file) == '')
	   {
	   		confirm('Please select image file to upload. Allowed file types are gif, jpg, jpeg and png.');
			
			$("form").attr("onSubmit", "return false;");
			
		    $('#upload-form-control').show();
		    $('#upload-progress').fadeOut("slow");
			
	   }else{
	   		$("form").attr("onSubmit", "return true;");
	   }
	   
	   document.getElementById('myForm').target = "upload_target";
	} else {
		// Clear attributes for form control
	   document.getElementById('myForm').target = "";
	   
	}
	document.getElementById('myForm').submit();
}

function stopUpload(success)
{
	alert(success);
	$('#upload-form-control').show();
	$('#upload-progress').fadeOut("slow");

	 if(success == '1')
	 {
	 	 alert('Please select image file to upload. Allowed file types are gif, jpg, jpeg and png.');
	 } else if (success == '-1') {

	 	alert('Directory does not exist.');

	 } else if (success == '2') {

	 	alert('File Size too big. File upload must have size under 2M.');

	 } else if(success != '-1' && success != '0' && success != '1' && success != '2'){
	 
		$("#previewField").html('<img src="'+success+'" alt="Preview image">'); 
		$('#image_file_upload').html('<input name="uploadFile" id="uploadFile"  type="file" class="step1-file-input" onChange="submitFormControl(\'upload\');"  size="10" />');
	 }
     return true;
}

function addNewTextBox(name)
{
	 var length = parseInt($("#"+name+"_length").val());
	 var nbr_length = parseInt($("#"+name+"_nbr_length").val());
	 var str = "<div style=\"boder:red solid 1px; \"></div><div class=\"step4-dot\">"+(nbr_length+1)+".</div>"+"\n";
	 	 str += "<input type=\"text\" id=\""+name+"_skill\" name=\""+name+"_skill[]\" value=\"\" class=\"short-textform step4-long-input\" />"+"\n";
	 $("#add_"+name).append(str);
	 $("#space").html("<div style=\"padding-top:10px;\"></div>");
	 $("#"+name+"_length").attr("value", length+1);
	 $("#"+name+"_nbr_length").attr("value", nbr_length+1);
}

function onlynumber(e) {
	var key;
	var keychar;
	var reg;
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode; 
	}

	else if(e.which) {
		// netscape
		key = e.which; 
	}
	else {
		// no event, so pass through
		return true;
	}
	keychar = String.fromCharCode(key);
	reg = /[\d\b]/;
	return reg.test(keychar);
}

/**
  * Change Town --> load company	
  * @Author : ManhND
*/
function loadCompany(townId, baseURL)
{
	var totalElement = baseURL.split('~~~~');
	if (totalElement[1])
	{
		baseURL = totalElement[1];
		totalElement = '-' + totalElement[0];
	} else {
		totalElement = '';
	}
	
	$("#company_id"+totalElement).html("<option value=''>Loading...</option>");
		
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=town&town_id="+townId,
		success: function(html)
		{
			$("#company_id"+totalElement).html(html);
			$('#company_id'+totalElement+' :first').attr('selected', 'selected');
		}
	});
}

/**
  * Disable "VIEW CV" button and Visible "<<" button on Preview CV
*/
function switchButton(disable_id,visible_id)	
{
	$('#'+disable_id).hide();
	$('#'+visible_id).show();
	$('#show_cv').toggle('slow');
}

function addElementOption(id, value)
{
	$("#"+id).html("<option value="+value+">"+value+"</option>");
}

function onlynumber(e) {
	var key;
	var keychar;
	var reg;
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode; 
	}

	else if(e.which) {
		// netscape
		key = e.which; 
	}
	else {
		// no event, so pass through
		return true;
	}
	keychar = String.fromCharCode(key);
	reg = /[\d\b]/;
	return reg.test(keychar);
}
function submitApplicant(baseURL)
{
	var username = $('#tex_username').val();
	var password = $('#tex_password').val();
	setMessage('');
	
	if(username == '') 
	{
		setMessage('You have not completed the following box: Username!');
		return;
	}
	if(password == '') 
	{
		setMessage('You have not completed the following box: Password!');
		return;
	}
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=ajax&username="+username+"&password="+password,
		success: function(html)
		{
			if(html =='1'){//success
				document.form_login.submit();	
			}else{//fail
				setMessage('Username or password is incorrect. Please try again');
			}
		}
	});
}
function setMessage(html)
{
	$('#login-message').html(html);
	if (html)
	{
		$('#login-message').show();
	} else {
		$('#login-message').hide();
	}
}
function loginkeyDown(e,baseURL ) 
{ // handles keypress
	var k = 0;
    if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = window.event.keyCode; 
	}else if(e.which) {
		// netscape
		key = e.which; 
	}
	if (k == 13) submitApplicant(baseURL);
}
