// JavaScript Document
function num_only(id)
{
	var field = document.getElementById(id);
	if(field.value.match(/[^0-9\.\-]/))field.value=field.value.replace(/[^0-9\.\-]/g,'');
}
function to_num(data)
{
	var i = 0;	
	if(data.length > 0)
	{
	 var i = parseFloat(data);
	}
	
	return i;
}

function to_amount(amount)
{
	if (isNaN(amount))
	{
		amount = 0;
	}
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function validate_news()
{
	var news_name = $('#news_name_input').val();
	var news_email = $('#news_email_input').val();
	var res = true; 
	var msg = "<p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>Please check the following errors:-<ul>";
		if(news_name.length == 0)	
		{
			res = false;
			msg += "<li>Please provide your Name.</li>";
		}
		if(!news_email.match(/^\w+([\.\-]\w+)*@\w+([\.\-]\w+)*\.[a-z]{2,4}$/i))
		{
			res = false;	
			msg += "<li>Please provide a valid email address.</li>";			
		}					
	msg += "</ul></p>";				
	if(res == false)				
	{
		$('#dialog').html(msg);				
		$('#dialog').dialog('open');				
		return false;				
	}
	else return true;		
}
function clear_values(div_id)
{//function to clear all the inputs within a div. 
	   ///      get the container DIV
            var div = document.getElementById(div_id);
            ///      get all INPUT elements within the DIV
            var inputs = div.getElementsByTagName('input');
			//alert(inputs.length);
            for(var i=0; i<inputs.length; i++)
            {
				if(inputs[i].type == 'text'|| inputs[i].type=='password') {
                        inputs[i].value = "";
                  }else if(inputs[i].type == 'radio'){
                        inputs[i].checked = false;
                  }else if(inputs[i].type == 'checkbox'){
                        inputs[i].checked = false;
                  }else if(inputs[i].type == 'select-one'){
                        inputs[i].selectedIndex = -1;
                  }else if(inputs[i].type == 'select-multiple'){
                        inputs[i].selectedIndex = -1;
                  };				
			}
}

function DaysArray(n) {

	for (var i = 1; i <= n; i++) {

		this[i] = 31

		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}

		if (i==2) {this[i] = 29}

   } 

   return this

}
// Declaring valid date character, minimum year and maximum year

var dtCh= "/";

var minYear=1900;

var maxYear=2100;



function isInteger(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;

}
function stripCharsInBag(s, bag){

	var i;

    var returnString = "";

    // Search through string's characters one by one.

    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++){   

        var c = s.charAt(i);

        if (bag.indexOf(c) == -1) returnString += c;

    }

    return returnString;

}



function daysInFebruary (year){

	// February has 29 days in any year evenly divisible by four,

    // EXCEPT for centurial years which are not also divisible by 400.

    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

}


function check_date(dtStr){
	var data = new Array();
	result = true;
	var message = "";
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		message += "<li>The date format should be : dd/mm/yyyy</li>";
		result = false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		message +="<li>Please enter a valid month at start/end date fields.</li>";
		result = false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		message +="<li>Please enter a valid day at start/end date fields.</li>";
		result= false;
	}
	if (strYear.length != 4 || year==0){
		message +="<li>Please enter a valid 4 digit year between "+minYear+" and "+maxYear+"</li>";
		result = false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		message += "<li>Please enter a valid date at start/end date fields.</li>";
		result = false;
	}
	data = [result,message];
return data;
}

function formatTwitString(str){
	// This function formats the tweet body text
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	// The tweets arrive as plain text, so we replace all the textual URLs with hyperlinks
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
	// Replace the mentions
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
	// Replace the hashtags
	return str;
}

function relativeTime(pastTime){
	// Generate a JavaScript relative time for the tweets
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	var difference = parseInt((currentStamp - origStamp)/1000);
	if(difference < 0) return false;
	if(difference <= 5)          return "Just now";
	if(difference <= 20)         return "Seconds ago";
	if(difference <= 60)         return "A minute ago";
	if(difference < 3600)        return parseInt(difference/60)+" minutes ago";
	if(difference <= 1.5*3600)   return "One hour ago";
	if(difference < 23.5*3600)   return Math.round(difference/3600)+" hours ago";
	if(difference < 1.5*24*3600) return "One day ago";
	// If the tweet is older than a day, show an absolute date/time value;
	var dateArr = pastTime.split(' ');
	//return dateArr[2]+' '+dateArr[1]+
	//(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
	return +' '+dateArr[2]+' '+dateArr[1]+
	(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
	
}

function relativeTime(time_value){
	  var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'about a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*60)) {
      return 'about an hour ago';
      } else if(delta < (24*60*60)) {
      return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
      return '1 day ago';
      } else {
      return (parseInt(delta / 86400)).toString() + ' days ago';
      }
	
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function searchFocus(txt)
{
    if(txt.value == 'Search the site...')
    {
        txt.value = '';
    }
}

function searchBlur(txt)
{
    if(txt.value == '')
    {
        txt.value = 'Search the site...';
    }
}


$(document).ready(function() 
{
			// Dialog			
			$('#dialog').dialog({
				autoOpen: false,
				title:'TWD Accountants',
				modal:true,
				width: 450,
				buttons: {
					"Ok": function() { 
						$(this).dialog("close"); 
						$('#dialog').html(""); 
					}
				}
			});
			
			// Findout More Dialog 
			$('#findout_more').dialog({
				autoOpen: false,
				modal:true,
				width: 650,
				buttons: {
					"Close": function() { 
						$(this).dialog("close"); 
					}
				}
			});
			

			var getHeight =  $('.the_menu').height();
			$('#top_menu_login_area').height(getHeight+40);
			$("img.menu_class").click(function () {
				if ($("ul.the_menu").is(":hidden")) {
				  $("ul.the_menu").slideDown();
				  
				} else {
				  $("ul.the_menu").slideUp();
				}
			});	
			$("#top_menu_login_area").hover( 
				function () {}, // hover on
				function () {	// hover off
				  $("ul.the_menu").slideUp();
				}
			);
});	
