$(document).ready( 
	function(){
		
		var base_url = $('#base_url').val();
		// Topic Type
		$("#btn-update-topic").click(
			function(){
				var check = validAction('update', 'topic_id');
				if(check==true)
				{
					var id = $('input[@name="topic_id"]:checked').val();
					var countryId = $('#country_id').val();
					var urllink = base_url + "/physcscoring/add"+"/country_id/" + countryId + "/no/" + id ;
					document.location.href=urllink;
				}
			}
		);
		
		$("#btn-delete-topic").click(
			function(){
				var check = validAction('delete', 'topic_id');
				if(check==true)
				{
					var id = $('input[@name="topic_id"]:checked').val();
					var urllink = base_url + "/physcscoring/deletetopic/no/" + id;
					if(confirm("Are you sure you want to delete this item?"))
					{
						document.location.href = urllink;
					}
					return false;
				}
			}
		);
		
		$("#scoring_clone_button").click(
			function(){
				var check = validAction('clone', 'topic_id');
				if(check==true)
				{
					var id = $('input[@name="topic_id"]:checked').val();
					
					$("#tnvAddClone").show();
					
					$('#clone_button_score').click
					(
						function ()
						{
							var countryIdClone = $('#countryId').val();
							var countryId      = $('#country_id').val();
							var urllink = base_url + "/physcscoring/clonescoring"+"/country_id_clone/" + countryIdClone + "/country_id/"+countryId+"/no/" + id ;
							document.location.href = urllink;
						}
					);
				}
			}
		);
	}
);

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document;if(d.images){if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){d.MM_p[j]=new Image;d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;document.MM_sr=new Array;for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;if(!x.oSrc) x.oSrc=x.src;x.src=a[i+2];}
}
function form_submit(id){
	var frm_object = document.getElementById(id);
	frm_object.submit();
}
function popup(url, width, height) {
  window.open(url,"_blank","width=" + width + ",height=" + height + ",toolbar=0,location=0,directories=0,resizable=1,status=0,menubar=0,scrollbars=0");
}

function popup2(url, width, height, scrollbars) {
  window.open(url,"_blank","width=" + width + ",height=" + height + ",toolbar=0,location=0,directories=0,resizable=1,status=0,menubar=0,scrollbars=" + scrollbars);
}

function popupLarge(url, target) {
  window.open(url,target);
}


function openwin(url,w_title,width,height)
{
	var maxw = window.screen.availWidth;
	var maxh = window.screen.availHeight;
	if(width > maxw) width = maxw;
	if(height > maxh) height = maxh;
	var win = window.open(url,w_title,'screenX=0,screenY=0,left='+((maxw-width)/2)+',top=0,width=' + width + ',height=' + height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,titlebar=no');
	win.focus();
	return win;
}

function openwin_scroll(url,w_title,width,height)
{
	var maxw = window.screen.availWidth;
	var maxh = window.screen.availHeight;
	var win = window.open(url,w_title,'screenX=0,screenY=0,left='+((maxw-width)/2)+',top=0,width=' + width + ',height=' + height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no');
	win.focus();
	return win;
}
function openwin_scroll_resize(url,w_title,width,height)
{
	var IE = /*@cc_on!@*/false;
	var maxw = window.screen.availWidth;
	var maxh = window.screen.availHeight;
	if(IE)
	{
		width = 800;
		height = 1200;
	}
	var win = window.open(url,w_title,'screenX=0,screenY=0,left='+((maxw-width)/2)+',top=0,width=' + width + ',height=' + height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no');
	win.focus();
	return win;
}
function body_img_onload()
{
	MM_preloadImages('');
	//alert("hello");
}
/**********************************************************/
function find_PosX(obj) 
{
  var curleft = 0;
  if (obj.offsetParent) 
  {
    while (obj.offsetParent) 
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function find_PosY(obj) 
{
    var curtop = 0;
    if (obj.offsetParent) 
    {
        while (obj.offsetParent) 
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function xstooltip_show(id, description, tooltip_id)
{
	//alert(description);
	//alert(tooltip_id);
	var obj_tooltip = document.getElementById(tooltip_id);
	var obj = document.getElementById(id);
	//alert(obj.width);
	//alert(obj.height);
	var obj_width = obj.width;
	var obj_height = obj.height;
	
	if(description)
	{
		obj_tooltip.innerHTML = description;
		obj_tooltip.style.top=find_PosY(obj) + 'px';
		obj_tooltip.style.left=find_PosX(obj) + obj_width + 6 + 'px';
		obj_tooltip.style.visibility = 'visible';
	}
}

function xstooltip_hide(id)
{
    var obj = document.getElementById(id); 
    obj.style.visibility = 'hidden'; 
}

function pageSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  var arr = new Array(myWidth, myHeight);
  return arr;
}

function Browser_W()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myWidth;
}

function Browser_H()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function winMove(popW, popH)
{
	var winleft = (screen.width - popW) / 2;
	var winUp = (screen.height - popH) / 2;
	window.moveTo(winleft,winUp-50);
}

function checkKeypress(e)
{
	var key = window.event ? e.keyCode : e.which;
	return key;
}

function textCounter(_id, maxlimit)
{
	//alert(id.value);
	var field = document.getElementById(_id);
	if(field)
	{
		//alert(field.value);
		if (field.value.length > maxlimit) // if too long...trim it!
		{
			field.value = field.value.substring(0, maxlimit);
		}
	}
}

function hideDropdowns()
{
	// looping through all forms on the page
	for (f = 0; f < document.forms.length; f++)
	{
		var elements = document.forms[f].elements;
		// looping through all elements on certain form
		for (e = 0; e < elements.length; e++)
		{
			if (elements[e].type == "select-one")
			{
				elements[e].style.display = 'none';
			}
		}
	}
}

function showDropdowns()
{
	// looping through all forms on the page
	for (f = 0; f < document.forms.length; f++)
	{
		var elements = document.forms[f].elements;
		// looping through all elements on certain form
		for (e = 0; e < elements.length; e++)
		{
			if (elements[e].type == "select-one")
			{
				elements[e].style.display = 'block';
			}
		}
	}
}
/**********************************************************/

/**
 * Process Array
*/
/**********************************************************/
function detectItem(originalArray, itemToDetect) {
	var j = 0;
	while (j < originalArray.length) {
		if (originalArray[j] == itemToDetect) {
			return true;
		} else { 
			j++; 
		}
	}
	return false;
}

//remove item (string or number) from an array
function removeItem(originalArray, itemToRemove) {
	var j = 0;
	while (j < originalArray.length) {
		// alert(originalArray[j]);
		if (originalArray[j] == itemToRemove) {
			originalArray.splice(j, 1);
		} else { 
			j++; 
		}
	}
	// assert('hi');
	return originalArray;
}
/**********************************************************/

function checknumber(x){
	var anum=/(^\d+$)|(^\d+\.\d+$)/
	if (anum.test(x))
		testresult=true;
	else{
		testresult=false;
	}
	return (testresult);
}

function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
	{
		return true;
	}  
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	{
	   myfield.form.elements[dec].focus();
	   return false;
	}
	else
		alert("Please input only number");
		return false;
}

function number_and_decimal_point_only(myfield, e, dec, current_value)
{
	var key;
	var keychar;
	
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	keychar = String.fromCharCode(key);
	//alert(key);
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) || (key==46))
	{
		if(key==46)
		{
			//alert(myfield.value);
			//alert(substr_count(myfield.value, "."));
			var count_point_decimal = substr_count(myfield.value, ".");
			if(parseInt(count_point_decimal)>0)
			{
				alert("Can not input other decimal point");
				return false;
			}
		}
		return true;
	}  
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	// decimal point jump
	else if (dec && (keychar == "."))
	{
	   return true;
	}
	else
		alert("Please input number and decimal point");
		return false;
}

/**
* Validate the string that contain specials characters (ex: '', null, 'Select', 'Loading')
* @param: str String
* @return: true/false
*/
function validateSpecialText(str)
{
	var valueArray = new Array('', null, 'select', 'Select', 'loading...', 'loading', 'Loading...', 'Loading');
	if(in_array(str, valueArray))
	{
		//alert("False");
		return false;
	}
	str = str_ireplace(' ', '', str);
	str = str_ireplace('-', '', str);
	str = str.toLowerCase();
	var valueArray = new Array('select', 'loading', 'defined');
	for(x in valueArray)
	{
		//alert(valueArray[x]);
		if(str.indexOf(valueArray[x])!=-1)
		{
			return false;
		}
	}
	return true;
}

function addAnother(baseURL)
{
	var totalElement = parseInt($('#totalElement').val())+1;
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=addAnswer&totalElement="+totalElement,
		success: function(html)
		{
			$("#addNewScore").before(html);
			$('#totalElement').val(totalElement);
		}
	});
}

function checkClientStatusSelected(name)
{
	var flag=false;
	$('input[@name="'+name+'"]').each(
		function(){
			if(this.checked==true)
			{
				flag=true;
			}
		}
	);
	return flag;
}

function validAction(type, name)
{
	var check = checkClientStatusSelected(name);
	if(check==false)
	{
		switch(type)
		{
			case "update":
				alert("Please select an Item to Update");
				return false;
				break;
			case "delete":
				alert("Please select an Item to Delete");
				return false;
				break;
			case "clone":
				alert("Please select an Item to Clone");
				return false;
				break;
		}
	}
	return true;
}

function validateForm ()
{
	var totalElement   		= $('#totalElement').val();
	var valueClient    		= 'answer_client_';
	var valueApplicant 		= 'answer_applicant_';
	var valuePointRangeFrom = 'score_from_';
	var valuePointRangeTo   = 'score_to_';
	var errorClient	   		= '';
	var errorApplicant 		= '';
	var errorPointRange 	= '';
	var message		   		= '';
	
	for(var i=1; i <= totalElement; i++)
	{
		if ($('#'+valueClient+i).val() == '')
		{
			errorClient    += i + ' ';
		} 
		if ($('#'+valueApplicant+i).val() == '') 
		{
			errorApplicant += i + ' ';
		}
		
		if (parseInt($('#'+valuePointRangeTo+i).val()) <= parseInt($('#'+valuePointRangeFrom+i).val()))
		{
			
			errorPointRange += i + ' ';
		}
		
	}
	
	if (errorClient != '' || errorApplicant != '' || errorPointRange != '')
	{
		if (errorClient != '') {message += '- Data in Client field is not empty [ANSWER]: ' + errorClient + '\n';};
		if (errorApplicant != '') {message += '- Data in Applicant field is not empty [ANSWER]: ' + errorApplicant + '\n';};
		if (errorPointRange != '') {message += '- Data in Point Range To field must great than Point Range From [ANSWER]: ' + errorPointRange;};
		alert(message);
	} else {
		document.frmScoring.submit();
	}
}

function addBulletPoint(baseURL)
{
	var totalElement = parseInt($('#totalBullet').val())+1;
	$.ajax({
		type: "POST",
		url : baseURL,
		data: "type=addBullet&totalElement="+totalElement,
		success: function(html)
		{
			$("#add-bullet").before(html);
			$('#totalBullet').val(totalElement);
		}
	});
}

function removeElement(idDel, idTotal) 
{
	var totalElement = $('#'+idTotal).val();
	
	if (idDel == '1' || idDel == '2')
	{
		alert('Bullet Points must exist at least two elements!');
		return;
	}
	if (confirm('Are you want to delete this item?'))
	{
		for(var i = idDel; i <= totalElement; i++)
		{
			$('#type_id_'+i).val($('#type_id_'+(parseInt(i)+1)).val());
			$('#headline_'+i).val($('#headline_'+(parseInt(i)+1)).val());
		}
		
		$('#bullet_'+totalElement).remove();
		$('#totalBullet').val(parseInt(totalElement)-1);
	}	
	return false;
}

function removeAnswer(idDel, idTotal) 
{
	var totalElement = $('#'+idTotal).val();
	
	if (idDel == '1' || idDel == '2' || idDel == '3')
	{
		alert('Bullet Points must exist at least two elements!');
		return;
	}
	if (confirm('Are you want to delete this item?'))
	{
		for(var i = idDel; i <= totalElement; i++)
		{
			$('#score_from_'+i).val($('#score_from_'+(parseInt(i)+1)).val());
			$('#score_to_'+i).val($('#score_to_'+(parseInt(i)+1)).val());
			$('#answer_client_'+i).val($('#answer_client_'+(parseInt(i)+1)).val());
			$('#answer_applicant_'+i).val($('#answer_applicant_'+(parseInt(i)+1)).val());
		}
		
		$('#scoring-'+totalElement).remove();
		$('#totalElement').val(parseInt(totalElement)-1);
	}	
	return false;
}

function validateFormContent()
{
	var message				    = '';
	var page				    = $('#page').val();
	var glanceHeadline 		    = $('#glance_headline').val();
	var glanceBody 			    = $('#glance_body').val();
	
	var characteristicHeadline  = $('#characteristic_headline').val();
	var characteristicBody 	    = $('#characteristic_body').val();
	
	var idealJobHeadline 	    = $('#ideal_job_headline').val();
	var idealJobBody 		    = $('#ideal_job_body').val();
	
	var personalityTypeHeadline = $('#personality_type_headline').val();
	var personalityTypeBody     = $('#personality_type_body').val();
	
	var famousHeadline 			= $('#famous_headline').val();
	var famousBody 				= $('#famous_body').val();
	
	var workplaceHeadline 		= $('#workplace_headline').val();
	var workplaceBody 			= $('#workplace_body').val();
	
	var totalElement   		    = $('#totalBullet').val();
	var errorHeadline	   		= '';
	
	for(var i=1; i <= totalElement; i++)
	{
		if ($('#headline_'+i).val() == '')
		{
			errorHeadline    += i + ' ';
		} 
	}
	var mess = 'bien';
	
	if ( glanceHeadline == '' ) {message += '- Pls. Fill data in the Headline field of [Your at a Glace]. \n';}
	if ( glanceBody == '') {message += '- Pls. Fill data in the Body Copy field of [Your at a Glace]. \n';}
	
	if ( characteristicHeadline == '') {message += '- Pls. Fill data in the Headline field of [Personality Characteristics]. \n';}
	if ( characteristicBody == '') {message += '- Pls. Fill data in the Body Copy field of [Personality Characteristics]. \n';}
	if ( errorHeadline != '') {message += '- Pls. Fill data in the Headline Bullet field of [Personality Characteristics]: ' + errorHeadline + '\n';};
	
	if ( personalityTypeHeadline == '') {message += '- Pls. Fill data in the Headline field of [Your Personality Types]. \n';}
	if ( personalityTypeBody == '') {message += '- Pls. Fill data in the Body Copy field of [Your Personality Types]. \n';}
	
	if (page == 1)
	{
		if (idealJobHeadline == '') {message += '- Pls. Fill data in the Headline field of [Your Ideal Jobs]. \n';}
		if (idealJobBody == '') {message += '- Pls. Fill data in the Body Copy field of [Your Ideal Jobs]. \n';}
	
		if (famousHeadline == '') {message += '- Pls. Fill data in the Headline field of [Famous People]. \n';}
		if (famousBody == '') {message += '- Pls. Fill data in the Body Copy field of [Famous People]. \n';}
	} else {
		if (workplaceHeadline == '') {message += '- Pls. Fill data in the Headline field of [In The Workplace]. \n';}
		if (workplaceBody == '') {message += '- Pls. Fill data in the Body Copy field of [In The Workplace]. \n';}
	}
	
	if (message != '')
	{
		alert(message);
	} else {
		document.frmContent.submit();
	}
	
}

function clearContent(headline, bodycopy)
{
	if(confirm("Are you sure you want to delete content of this item?"))
	{
		$('#'+headline).val('');
		$('#'+bodycopy).val('');
	}
}

/*
 * copy from \pumphouse\themes\bigsplash\js\invoicestosend.js
 * For open invoice in popup
 */
function openwinInv(url,w_title,width,height){
	var maxw = window.screen.availWidth;
	var maxh = window.screen.availHeight;
	var win = window.open(url,'blank','screenX=0,screenY=0,left='+((maxw-width)/2)+',top=0,width=' + width + ',height=' + height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no');
		win.focus();
	return false;
}

function emailInvoice(invoice_id){
    var base_url = $('#base_url').val();
    url = base_url + '/clientinvoiceall/sendMailInvoice/id/' +invoice_id;
    openwinInv(url,"email_invoice",900,700);
    return false;
}

var FormValid = {
	isInteger: function(s){
		var i;
		for (i = 0; i < s.length; i++){
			// Check that current character is number.
			var c = s.charAt(i);
			if (((c < "0") || (c > "9"))) return false;
		}
		// All characters are numbers.
		return true;
	},

	isNumeric: function(sText)
	{
	   var ValidChars = "0123456789.";
	   var IsNumber=true;
	   var Char;

	   for (i = 0; i < sText.length && IsNumber == true; i++)
		  {
		  Char = sText.charAt(i);
		  if (ValidChars.indexOf(Char) == -1)
			 {
			 IsNumber = false;
			 }
		  }
	   return IsNumber;
	},

    //allow negative value
	isMoneyAmount: function(sText)
	{
	   var ValidChars = "0123456789.-";
	   var IsNumber=true;
	   var Char;

	   for (i = 0; i < sText.length && IsNumber == true; i++)
		  {
		  Char = sText.charAt(i);
		  if (ValidChars.indexOf(Char) == -1)
			 {
			 IsNumber = false;
			 }
		  }
	   return IsNumber;
	},

    dateDiff: function(date1, date2){
        if (date2 > date1) {
            return 2;
        }else if (date2 == date1) {
            return 1;
        }else{
            //date2 < date1
            return 0;
        }
    },

	end : 0
}
