// JavaScript Document

/*
* This will get the relative url when ajax calls
*/
var path = location.href;
temp = path.split('/');
var urlPath = "";
for(i = 3; i < temp.length-1; i++) {
	urlPath = urlPath + "/" + temp[i];
}

/*
* Get the url path excluding the current controller
*/
var pdfPath = "";
for(i = 3; i < temp.length-1; i++) {
	pdfPath = pdfPath + "/" + temp[i];
}

var r = {
  'special':/[^a-zA-Z0-9_,.\s]/g,
  'alpha': /[^A-zÑñ\s]/g,
  'digit': /[^\d]/g,
  'float': /[^\d.]/g,
  'telno': /[^\d+-]/g
}

function valid(o,w)
{
	o.value = o.value.replace(r[w],'');
}

var sURL = unescape(window.location.pathname);

function doLoad()
{
    refresh();
}

function refresh()
{
    //  This version of the refresh function will cause a new
    //  entry in the visitor's history.  It is provided for
    //  those browsers that only support JavaScript 1.0.
    //
    window.location.href = sURL;
}

function refresh()
{
    //  This version does NOT cause an entry in the browser's
    //  page view history.  Most browsers will always retrieve
    //  the document from the web-server whether it is already
    //  in the browsers page-cache or not.
    //  
    window.location.replace( sURL );
}

function refresh()
{
    //  This version of the refresh function will be invoked
    //  for browsers that support JavaScript version 1.2
    //
    
    //  The argument to the location.reload function determines
    //  if the browser should retrieve the document from the
    //  web-server.  In our example all we need to do is cause
    //  the JavaScript block in the document body to be
    //  re-evaluated.  If we needed to pull the document from
    //  the web-server again (such as where the document contents
    //  change dynamically) we would pass the argument as 'true'.
    //  
    window.location.reload( false );
}

// check if the element exist
function elExist(e)
{
	if(e.length > 0) return true;
	else false;
}

/* 
* Get the selected tr
*/
function fnGetSelected( oTableLocal, tr_id )
{
	var aReturn = new Array();
	var aTrs = oTableLocal.fnGetNodes();
	
	for ( var i=0 ; i<aTrs.length ; i++ )
	{
		if ( $(aTrs[i]).attr('id') == tr_id )
		{
			aReturn.push( aTrs[i] );
		}
	}
	
	return aReturn;
}

// add commas to numbers
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/*
 * This is a javascript version of in_array function in PHP
 */
function in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false

    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

/*
 * Close the table when showing particaular details of the application
*/
function closeTable(id, imgId)
{
	var anSelected = fnGetSelected( oTable, id );
	$(imgId).attr("src", pdfPath+"/media/images/details_open.png");
	oTable.fnClose( anSelected[0] );
}

/*
 * Clear fields in the form
 */
function clear_form_elements(ele) {
    $(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
}

function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + jsFile + '"></scr' + 'ipt>'); 
}


/*
 * Display loading image until ajax process is not complete
 */
function loading()
{
	var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
		sOut += '<tr><td style="text-align: center;">Loading ... Please Wait ...<br /></td></tr>';
		sOut += '</table>';
	
	return sOut;
}

/*
 * Display loading state 
 */
function waiting()
{
	$.blockUI({ css: { 
		border: 'none', 
		padding: '15px', 
		backgroundColor: '#669933', 
		'-webkit-border-radius': '10px', 
		'-moz-border-radius': '10px', 
		opacity: .6, 
		color: '#fff' 
	} });	
}

/*
* Trim whitespaces on a string
*/
function trim (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	
	return str.slice(0, i + 1);
}

/*
* Check if there are fields that are empty
*/
function isEmpty( arrFields )
{
	for(i=0; i<arrFields.length; i++)
	{
		value = trim( $(arrFields[i]).val() );
		if( value == "" ) return true;
	}
	
	return false;
}

// get the current year
function getCurrentYear()
{
	var d = new Date();
	return d.getFullYear();	
}

/*
 * Open a dialog for editing user profile
 */
function openDialog(ids)
{
	waiting();
	$.ajax({
		type: "POST",
		data: "clientid=" + ids[2],
		url: urlPath + "/agentajax/ajaxGetUserDetails",
		success: function(msg) {
			msgs = msg.split('|-|');
			$('#div-personal-info').html(msgs[0]);
			$('#div-employment-info').html(msgs[1]);
			$('#div-educational-info').html(msgs[2]);
			$('#div-income-info').html(msgs[3]);
			$('#div-spouse-info').html(msgs[4]);
			$('#div-child-info').html(msgs[5]);
		},
		complete: function() {
			$.unblockUI();
			range = '1960:'+getCurrentYear();
			$("#cbday").datepicker({
				changeMonth: true,
				changeYear: true,
				dateFormat: 'yy-mm-dd',
				yearRange: range
			});
			$("#sbday").datepicker({
				changeMonth: true,
				changeYear: true,
				dateFormat: 'yy-mm-dd',
				yearRange: range
			});
			$('#dialog-edit-client').dialog('open');	
		}
	});
}

// successfully saving the update in the user profile
function profileSaved()
{
	var arrval = new Array();
	arrval = formFields();
	
	$('#form-message').html('<div class="icon-yellow">Loading...</div>');
	$.ajax({
		type: "POST",
		data: "arrval=" + arrval,
		url: urlPath+"/agentajax/ajaxSaveClientUpdates",
		success: function(msg) {},
		complete: function() {
			$('#form-message').html('<div class="icon-ok">Successfully saved!</div>');	
		}
	});
}

/*
* Make the fields in the array empty
*/
function emptyFields( arrFields )
{
	for(i=0; i<arrFields.length; i++) 
		$(arrFields[i]).val('');	
}

/*
* Check if the table has records
*/
function hasNoInfo(noInfoId)
{
	if( $(noInfoId).length == 0 ) return false;
	return true;
}

/*
* Highlight the selected row
*/
function selectedRow(table, trId)
{ 
	$(table+' tbody tr').each(function() { 
		if( $(this).attr('id') == trId )
		{
			$(this).css('backgroundColor', '#999999');
			$(this).css('color', '#FFF');
		}
		else 
		{
			$(this).css('backgroundColor', '#FFFFFF');
			$(this).css('color', '#000000');	
		}
	});
}

// This is Javascript, not PHP!
function js_array_to_php_array (a)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    return a_php;
}

/*
* Store the fields value in an array
*/
function storeValToArr( arrFields, trEmpId, dothis )
{
	var arrValues = new Array();
	var k = 0;
	if(dothis != "add") {
		arrValues[0] = trEmpId;
		k = 1;
	}
	for(i=0; i<arrFields.length; i++) {
		arrValues[i+k] = $(arrFields[i]).val();
	}
	
	return js_array_to_php_array( arrValues );
}

// get the equivalent attainment name
function showAttainment(attainid, path)
{
	return $.ajax({ 
					type: "POST", 
					data: "attainid=" + attainid, 
					async: false,
					url: path+'/ajaxGetAttainName',
					success: function(msg) {} 
				}).responseText;	
}

/*
 * This will do the add and update functionality in tables
*/
function addFunc(tableId, trId, tlbflds, noInfoId, addBtnId, table, path)
{
	var arrval = new Array();
	var i = 0;
	
	if( isEmpty(tlbflds) ) {
		alert('Please fill up all fields! (Type N/A if the fields is Not Applicable)');
	}
	else
	{
		if( $(addBtnId).attr('value') == "Add" )
		{
			if( hasNoInfo(noInfoId) ) $(noInfoId).remove();
			dothis = "add";
			arrval = storeValToArr(tlbflds, trId, dothis);
			data = "";
			$.ajax({
				  type: "POST",
				  data: "dothis=" + dothis + "&arrvalues=" + arrval + "&table=" + table + "&trId=" + trId,
				  url: path+"/ajaxTableUpdates",
				  success: function(msg) { 
						data = msg;
				  },
				  complete: function() {
					  	$(tableId).append(data);
				  }
			});
		}
		else
		{
			dothis = "update";
			arrval = storeValToArr(tlbflds, trId, dothis);
			$.ajax({
				  type: "POST",
				  data: "dothis=" + dothis + "&trId=" + trId + "&arrvalues=" + arrval + "&table=" + table,
				  async: false,
				  url: path+"/ajaxTableUpdates",
				  success: function(msg) {
				  	if(table == "educ") 
					{
						$(tableId+' #'+trId+' td').each(function() {							
							if(tlbflds[i] == '#educattain') {
								attainid = $(tlbflds[i]).val();
								$(this).text( showAttainment(attainid, path) );
							}
							else $(this).text( $(tlbflds[i]).val() );
							i++;
						});
					} 
					else if(table == "uemp")
					{ 
						$(tableId+' #'+trId+' td').each(function() {							
							if(i == 5) {
								$(this).text( $(tlbflds[i]).val() + '-' + $(tlbflds[i+1]).val() );
								return false;
							}
							else $(this).text( $(tlbflds[i]).val() );
							i++;
						});	
					}
					else
					{
						$(tableId+' #'+trId+' td').each(function() {
							$(this).text( $(tlbflds[i]).val() );
							i++;
						});
					}
				  }
			});
			$(addBtnId).attr('value', 'Add');
		}
		emptyFields(tlbflds);
	}	
}

/*
 * This will do the delete functionality in tables
*/
function deleteFunc(tableId, trId, tlbflds, noInfoId, addBtnId, table, noInfoText, path)
{
	$.ajax({
		type: "POST",
		data: "trId=" + trId + "&table=" + table,
		url: path+"/ajaxTableDelete",
		success: function(msg) {},
		complete: function() {
			$(tableId+' #'+trId).remove();
			emptyFields(tlbflds);
			$(addBtnId).attr('value', 'Add');
			if( $(tableId+' tbody tr').length < 1 ) {
				$(tableId).append('<tr id='+noInfoId.substr(1)+'><td colspan="6" align="center" class="td-highlight">'+noInfoText+'</td></tr>');
			}	
		}
	});
}

// remove ampersand in the input and replace with "and"
function delAmpersand(str)
{
	return str.replace("&", "and");
}

// Store the other fields in the form in an array
function formFields()
{
	var arrFields = new Array();
	var i = 0;
	// Personal Information
	arrFields[i] = "#cfname";		// 0
	arrFields[++i] = "#cmname";		// 1
	arrFields[++i] = "#clname";		// 2
	arrFields[++i] = "#cbday";		// 3
	arrFields[++i] = "#gender";		// 4
	arrFields[++i] = "#sssgsis";	// 5
	arrFields[++i] = "#tin";		// 6
	arrFields[++i] = "#marstat";	// 7	
	arrFields[++i] = "#cmobno";		// 8
	arrFields[++i] = "#ctelno";		// 9
	arrFields[++i] = "#cpreadd1";	// 10
	arrFields[++i] = "#cpreadd2";	// 11
	arrFields[++i] = "#cprecity";	// 12
	arrFields[++i] = "#cprezip";	// 13
	arrFields[++i] = "#cperadd1";	// 14
	arrFields[++i] = "#cperadd2";	// 15
	arrFields[++i] = "#cpercity";	// 16
	arrFields[++i] = "#cperzip";	// 17
	arrFields[++i] = "#cproadd1";	// 18
	arrFields[++i] = "#cproadd2"; 	// 19
	arrFields[++i] = "#cprocity";	// 20
	arrFields[++i] = "#cprozip";	// 21
	arrFields[++i] = "#homeowner";	// 22
	arrFields[++i] = "#landname";	// 23
	arrFields[++i] = "#landno";		// 24
	// Net Information
	arrFields[++i] = "#cmonthinc";	// 25
	arrFields[++i] = "#smonthinc";	// 26
	arrFields[++i] = "#otrincome";	// 26
	arrFields[++i] = "#fmonthinc";	// 28
	arrFields[++i] = "#otrlivex";	// 29
	arrFields[++i] = "#totmonthinc";	// 30
	arrFields[++i] = "#monthnetinc";	// 31
	// Spouse Information
	arrFields[++i] = "#sfname";			// 32
	arrFields[++i] = "#smname";			// 33
	arrFields[++i] = "#slname";			// 34
	arrFields[++i] = "#sbday";			// 35
	arrFields[++i] = "#scompname";		// 36
	arrFields[++i] = "#sadd";			// 37
	arrFields[++i] = "#spos";			// 38
	arrFields[++i] = "#stelno";			// 39
	arrFields[++i] = "#swoten";			// 40
	
	var arrValues = new Array();
	for(k=0; k<arrFields.length; k++) {
		arrValues[k] = delAmpersand( $(arrFields[k]).val() );
	}
	
	return js_array_to_php_array( arrValues );
}

// show the pdf
function viewPDF(appid)
{
	waiting();
	var data = "";
	$.ajax({
		type: "POST",
		data: "appid=" + appid,
		url: urlPath+"/ajaxupload/showPdf",
		success: function(msg) {
			data = msg;
		},
		complete: function() {
			$.unblockUI();
			if(data != "")
			{
				var features = "height=700,width=800,scrollTo,resizable=1,scrollbars=1,location=0";
				newwindow=window.open(data, 'Popup', features);
				return false;
			}
			else {alert("No uploaded documents!");}
		}
	});
}

function checkSession(id, file)
{
	return $.ajax({
				type: "POST",
				data: "id=" + id,
				async: false,
				url: urlPath+"/"+file+"/ajaxExpiredSession",
				success: function(msg) {}
		   }).responseText;
}

function expired(id, file)
{
	msg = checkSession(id, file);
	
	if(!msg) 
	{
		alert("Your session expired! Press OK to redirect to login.");
		doLoad();
	}
	
	return msg;
}

// remove the comma
function unformat(id)
{
	return Number(id.val().replace(/\,/g,''));	
}

// format the result value with comma
function format(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/* --- EDIT PROFILE --- */
// add row data
function fnAdd(tableId, trId, tblflds, path, addBtnId, table)
{
	var arrval = new Array();
	var i = 0;
	
	if( isEmpty(tblflds) ) {
		alert('Please fill up all fields! (Type N/A if the fields is Not Applicable)');
	}
	else
	{
		if( $(addBtnId).attr('value') == "Add" )
		{
			dothis = "add";
			arrval = storeValToArr(tblflds, trId, dothis);
			data = "";
			$.ajax({
				  type: "POST",
				  data: "dothis=" + dothis + "&arrvalues=" + arrval + "&table=" + table + "&trId=" + trId,
				  url: path+"/ajaxTableUpdates",
				  success: function(msg) {
						data = msg;
				  },
				  complete: function() {
					  	$(tableId).append(data);
				  }
			});
		}
		else
		{
			dothis = "update";
			arrval = storeValToArr(tblflds, trId, dothis);
			$.ajax({
				  type: "POST",
				  data: "dothis=" + dothis + "&trId=" + trId + "&arrvalues=" + arrval + "&table=" + table,
				  async: false,
				  url: path+"/ajaxTableUpdates",
				  success: function(msg) {
					$('#'+trId+' td').each(function() {
						$(this).text( $(tblflds[i]).val() );
						i++;
					});
				  }
			});
			$(addBtnId).attr('value', 'Add');
		}
		emptyFields(tblflds);
	}	
}

// confirm dialog box upon deletion of item(s)
function fnConfirm()
{
	var result = false;
	$("#dialog-confirm").dialog({
		autoOpen: false,
		resizable: false,
		closeOnEscape: false,
		modal: true,
		buttons: {
			'No': function() {
				result = false;	
			},
			'Yes': function() {
				result = true;	
			}
		}
	});
	
	return result;
}

/* --- EDIT PROFILE --- */
/*
 * This delete selected row in a table
*/
function fnDelete(tableId, trId, tblflds, addBtnId, table, path)
{
	
	$.ajax({
		type: "POST",
		data: "trId=" + trId + "&table=" + table,
		url: path+"/ajaxTableDelete",
		success: function(msg) {},
		complete: function() {
			$('#'+trId).remove();
			emptyFields(tblflds);
			$(addBtnId).attr('value', 'Add');	
		}
	});
}

/* Additional */
function handle_field(id)
{
	var id;
	var value;
	value = document.getElementById(id).value.toLowerCase();
	if (value == 'first' || value == 'm.i' || value == 'last')
	{
		document.getElementById(id).value = "";
	}
}
						
function is_empty(id)
{
	var id;
	var value;
	value = document.getElementById(id).value.toLowerCase();
	if (value == '')
	{
		switch (id)
		{
			case 'app-firstname': document.getElementById(id).value = "First"; break;
			case 'app-middlename': document.getElementById(id).value = "M.I"; break;
			case 'app-lastname': document.getElementById(id).value = "Last"; break;
			
			case 'txtFName': document.getElementById(id).value = "Last"; break;
			case 'txtMName': document.getElementById(id).value = "Last"; break;
			case 'txtLName': document.getElementById(id).value = "Last"; break;
		}
	}
}
