/*****************************************************************
 * Author: Stas Sakalou
 *
 * Global Java Script Functions
 *****************************************************************/
var COOKIE_QUOTE="quote1";
var COOKIE_LOGIN="login";
var COOKIE_PASSWORD="password";
var COOKIE_INVESTMENT_NAME="investment_name";
var COOKIE_PRICE_OF_REAL_ESTATE="price_of_real_estate";
var COOKIE_PRICE_GROW_HOUSE="price_grow_house";
var COOKIE_INTEREST_RATE="interest_rate_on_mortgage";
var COOKIE_MORTGAGE_DOWNPAYMENT="mortgage_downpayment_percent";
var COOKIE_TERM_OF_LOAN="term_of_loan";
var COOKIE_PRICE_OF_RENT="price_of_rent";
var COOKIE_PRICE_GROW_RENT="price_grow_rent";

var COOKIE_CLOSING_COST_TO_BUY="closing_cost_to_buy";
var COOKIE_CLOSING_COST_TO_SELL="closing_cost_to_sell";
var COOKIE_ANNUAL_REAL_ESTATE_TAX="annual_real_estate_tax";
var COOKIE_ANNUAL_MAINTANANCE="annual_maintenance";
var COOKIE_CONSIDER_TAXES_INCOME="consider_taxes_when_calculate_income_loss";
var COOKIE_CONSIDER_TAXES_PAYMENTS="consider_taxes_when_calculate_payments";
var COOKIE_ITEMIZED_DEDUCTION="itemized_deduction_type";

var COOKIE_TAX_RATE="tax_rate";


    function callAction(name)
    {
        callActionMethod(name,"POST");
    }

    function callActionMethod(name, method_type)
    {
        document.forms[0].method = method_type;
        document.forms[0].action = name;
        document.forms[0].submit();
    }

    /*****************************************************************
     * Go to home page HomePage.do
     *****************************************************************/
     function gotoHomePage()
     {
        goto("HomePage.do");
     }

    /*****************************************************************
     * Go to selected page
     *****************************************************************/
     function goto(prior_action)
     {
        document.forms[0].action=prior_action;
        document.forms[0].submit();
     }

    /*****************************************************************
     * Check that value of element is empty or space
     *****************************************************************/
     function isEmpty(s)
     {

        var res2=(s.value==null || trim(s.value).length == 0);
        return res2;
     }
      /*****************************************************************
     * Check that value of element is empty or space
     *****************************************************************/
     function isEmptyString(s)
     {
        return s==null || s.length == 0;
     }





     var dtCh= "/";
     var minYear=1900;
     var maxYear=2100;

    /*****************************************************************
     * Check that value is integer
     *****************************************************************/
     function isInteger(s)
     {
         s=trim(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;
     }

    /*****************************************************************
     * Delete spaces on the left and the rigth of the string
     *****************************************************************/
    function trim(sString)
    {
        while (sString.substring(0,1) == ' ')
        {
             sString = sString.substring(1, sString.length);
        }
        while (sString.substring(sString.length-1, sString.length) == ' ')
        {
            sString = sString.substring(0,sString.length-1);
        }
        return sString;
    }

    /*****************************************************************
     * Check that value is integer
     *****************************************************************/
     function isNumber(s)
     {
         if (s==null || s=='') return false;
         s=trim(s);
         s=s.replace(',',"");
         s=s.replace('\$',"");
         s=s.replace('\'',"");

         var i;

         for (i = 0; i < s.length; i++)
         {
             // Check that current character is number.
             var c = s.charAt(i);
             if (c=='-')
             {
                 if (i!=0)
                 {//- means negative but it should be a first character
                    return false;
                 }
             }
             else
             {
                if (((c < "0") || (c > "9")) && (c!='.')) 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 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
     }

    /***************************************************************************************************************
     * Get element by name
     ***************************************************************************************************************/
     function getElementByName(control_name)
     {
         if (document.getElementsByName(control_name)!=null)
         {
            return document.getElementsByName(control_name)[0];
         }
         else
         {
             return null;
         }
     }



     function validateNoneEmptyFields(list_of_fields)
     {
        var error_message = '';
        jQuery.each(list_of_fields, function(index, value) {
           error_message+=checkThatIsNotEmpty(value,message_empty_field);
         });
         return error_message;
     }

     function validateNumericFields(list_of_fields)
     {
        var error_message = '';
        jQuery.each(list_of_fields, function(index, value) {
           error_message+=checkThatIsNumber(value,message_empty_field);
         });
         return error_message;
     }
     function validatePositiveNumericFields(list_of_fields)
     {
        var error_message = '';
        jQuery.each(list_of_fields, function(index, value) {
           error_message+=checkThatIsPositiveNumber(value,message_empty_field);
         });
         return error_message;
     }

     function validatePositiveNonZeroNumericFields(list_of_fields)
     {
         var error_message = '';
         jQuery.each(list_of_fields, function(index, value)
         {
           error_message+=checkThatIsPositiveNumberGreaterThenZero(value,message_empty_field);
         });
         return error_message;
     }

     function checkThatURL(control_name)
     {
         var error_message = '';
         var control = getElementByName(control_name);
         var control_name_value = control.value;
         //ignore empty strings
         if (!isEmpty(control))
         {

            if (!isValidURL(control_name_value))
            {
                error_message+=errororize(control, message_invalid_url);
            }
         }
         return error_message;
     }

    function checkThatEmail(control_name)
     {
         var error_message = '';
         var control = getElementByName(control_name);
         var control_name_value = control.value;
         //ignore empty strings
         if (!isEmpty(control))
         {
            if (!isValidEmail(control_name_value))
            {
                error_message+=errororize(control, message_invalid_email);
            }
         }
         return error_message;
     }
    /***************************************************************************************************************
     * Remove spaces
     ***************************************************************************************************************/
     function removeSpaces(control_name)
     {
         var control  = getElementByName(control_name);
         if (!isEmpty(control))
         {
             control.value=replaceAll(control.value,' ','');
         }
     }
    /***************************************************************************************************************
    * Replace all occurencies of an element in text
     ***************************************************************************************************************/
    function replaceAll(txt, replace, with_this)
    {
        return txt.replace(new RegExp(replace, 'g'),with_this);
    }

    /***************************************************************************************************************
     * Check that controll is not empty
     ***************************************************************************************************************/
     function checkThatIsNotEmpty(control_name, localized_error_message)
     {

         var control  = getElementByName(control_name);

         var error_message='';
         if (isEmpty(control))
         {
             error_message=errororize(control, localized_error_message);

         }

         return error_message;
     }

    /***************************************************************************************************************
     * If element is not a date then highlight appropriate label.
     * provide message in the local language to be shown in case of error
     ***************************************************************************************************************/
     function checkThatIsDate(control_name, localized_error_message)
     {
         var control  = getElementByName(control_name);
         var error_message='';

         if (!isEmpty(control))
         {
             if (!isDate(control.value))
             {
                  error_message=errororize(control, localized_error_message);
             }
         }

         return error_message;
     }


    /***************************************************************************************************************
     * If element is not a date then highlight appropriate label.
     * provide message in the local language to be shown in case of error
     ***************************************************************************************************************/
     function checkThatIsNumber(control_name, localized_error_message)
     {
         var control  = getElementByName(control_name);
         var error_message='';
         if (!isEmpty(control))
         {
             control.value=control.value.replace('$',"");
             control.value=control.value.replace(',',"");
             control.value=control.value.replace('\'',"");

             if (!isNumber(control.value))
             {
                  error_message=errororize(control, localized_error_message);
             }
         }
         return error_message;
     }

     function checkThatIsPositiveNumber(control_name, localized_error_message)
     {
         var control  = getElementByName(control_name);
         var error_message='';
         if (!isEmpty(control))
         {
             if (isNumber(control.value))
             {
                  if (control.value<0)
                  {
                       error_message=errororize(control, localized_error_message);
                  }
             }
         }

         return error_message;
     }

    function checkThatIsPositiveNumberGreaterThenZero(control_name, localized_error_message)
     {

         var control  = getElementByName(control_name);
         var error_message='';
         if (!isEmpty(control))
         {
             if (isNumber(control.value))
             {
                  if (control.value<=0)
                  {
                       error_message=errororize(control, localized_error_message);
                  }
             }
         }

         return error_message;
     }
    /***************************************************************************************************************
     * If element is not a date then highlight appropriate label.
     * provide message in the local language to be shown in case of error
     ***************************************************************************************************************/
     function errororize(control, localized_error_message)
     {
          var control_name=control.name;
          var label_name = 'label.'+control_name;
          var control_label=document.getElementById(label_name);
          markErrorControl(control_name);
          return '<li><b>'+control_label.innerHTML+'</b>&nbsp;'+localized_error_message+'</li>';
     }

    /***************************************************************************************************************
     * Check that value is a valid Date
     ***************************************************************************************************************/
     function isDate(dtStr)
     {
                    var daysInMonth = DaysArray(12)
                    var pos1=dtStr.indexOf(dtCh)
                    var pos2=dtStr.indexOf(dtCh,pos1+1)
                    var strMonth=dtStr.substring(0,pos1)
                    var strDay=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){
                //		alert("The date format should be : mm/dd/yyyy")
                        return false
                    }
                    if (strMonth.length<1 || month<1 || month>12){
                //		alert("Please enter a valid month")
                        return false
                    }
                    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
                //		alert("Please enter a valid day")
                        return false
                    }
                    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
                //		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
                        return false
                    }
                    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
                //		alert("Please enter a valid date")
                        return false
                    }
                return true
    }



   /***************************************************************************************************************
    *   Highlight in red one error control
    ***************************************************************************************************************/
   function markErrorControl(s)
   {
        setClass("label."+s,"label_error");
   }

   /***************************************************************************************************************
    *   If element is label then remove a highlighting
    ***************************************************************************************************************/
   function resetColorForAllLabels()
   {

        var elements = document.getElementsByTagName("label");
        for (i=0; i < elements.length; i++)
        {
               var element = elements.item(i);
               element.className='';
        }
   }

   /***************************************************************************************************************
    *   Highlight as normal label
    ***************************************************************************************************************/
   function markNormalControlLabel(s)
   {
        setClass("label."+s,"");
   }

   /***************************************************************************************************************
    *   Highlight in red one error control
    ***************************************************************************************************************/
   function setClass(controlID,class_name)
   {
        var el=document.getElementById(controlID);
       if (el!=null)
       {
           el.className=class_name
       }
   }

   /***************************************************************************************************************
    *   Hide/Show HTML element using Java Script. Every call switch visibility mode
    ***************************************************************************************************************/
   function hideElementNoFlip(element)
   {

        var el = document.getElementById(element);
        if (el!=null)
        {
            el.style.display = 'none';
        }
   }
   
   /***************************************************************************************************************
    *   Hide/Show HTML element using Java Script. Every call switch visibility mode
    ***************************************************************************************************************/
   function hideElement(element)
   {
        var el = document.getElementById(element);
        if (el!=null)
        {
            if ( el.style.display != 'none' )
            {
                el.style.display = 'none';
            }
            else
            {
                el.style.display = '';
            }
        }
   }

   /***************************************************************************************************************
    * Hide error message window
    ***************************************************************************************************************/
   function hideError(error)
   {
       hideElement('error_table')
   }

   /***************************************************************************************************************
    *   Hide/Show HTML element using Java Script. Every call switch visibility mode
    ***************************************************************************************************************/
   function showElement(element)
   {
        var el = document.getElementById(element);
        if (el!=null)
        {
            el.style.display = '';
        }    
   }


  /***************************************************************************************************************
   * Show error stocks dialog
   ***************************************************************************************************************/
   function showErrorCentered(error,flag)
   {
       var x=document.getElementById('error_table_body').rows[1].cells;
       if (flag==1)
       {
           x[0].innerHTML="<center>"+error+"</center></br>";
       }
       else
       {
           x[0].innerHTML="<br>"+error;
       }

       showElement('error_table');
       ScrollToElement(document.getElementById('error_table'));    //http://p.rdcpix.com/v01/lcb83ec42-m0m.jpg
       //alert('xxx');
  }
  /***************************************************************************************************************
   * Show error stocks dialog
   ***************************************************************************************************************/
   function showError(error)
   {
       showError(error,1);
  }

function ScrollToElement(theElement){

  var selectedPosX = 0;
  var selectedPosY = 0;

  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }

 window.scrollTo(selectedPosX,selectedPosY);

}

/***************************************************************************************************************
 * Highlight positive and negative numbers by different collors
 ***************************************************************************************************************/
function colorNumber(value)
{
    if (value>0) return '<b><font color="green">$'+value+"</font></b>";
    if (value<0) return '<b><font color="red">$'+value+"</font></b>";
    return '$'+value;
}

/***************************************************************************************************************
 * Highlight positive and negative percents by different collors
 ***************************************************************************************************************/
function colorPercent(value)
{
    if (value>0) return '<b><font color="green">%'+value+"</font></b>";
    if (value<0) return '<b><font color="red">%'+value+"</font></b>";
    return '%'+value;
}

/***************************************************************************************************************
 * Get AJAX processor. Implementation depends on browser type
 ***************************************************************************************************************/
function getXMLProcessor()
{
    var request;

    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject))
    {
            try
            {
              request =  new XMLHttpRequest();
            }
            catch(e)
            {
                request = false;
            }
        // branch for IE/Windows ActiveX version
     }
    else
    if(window.ActiveXObject)
    {
        
       try
       {
            request = new ActiveXObject("Msxml2.XMLHTTP");
       }
       catch(e)
       {
            try
            {
                  request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                  request = false;
            }
      }
    }
    return request;
}

/***************************************************************************************************************
 * Get XML elements from AJAX request. Implementation depend on broweser type
 ***************************************************************************************************************/
function getElements(document,req1)
{
            var xmlDoc;

           //alert(req1.responseText);
            if ( document.implementation && document.implementation.createDocument )
            {
                xmlDoc = req1.responseXML;
            }
            else
            if (window.ActiveXObject)
            {//THIS SHIT DOES NOT WORK
                xmlDoc = req1.responseXML;
            /*
                //Create a xml tag in run time
                var testandoAppend = document.createElement('xml');
                //Put the requester.responseText in the innerHTML of the xml tag
                testandoAppend.setAttribute('innerHTML',req1.responseText);
                //Set the xml tag's id to _formjAjaxRetornoXML
                testandoAppend.setAttribute('id','_formjAjaxRetornoXML');
                //Add the created tag to the page context
                document.body.appendChild(testandoAppend);
                //Just for check put the xmlhttp.responseXML in the innerHTML of the tag
                document.getElementById('_formjAjaxRetornoXML').innerHTML = req1.responseText;
                //Now we can get the xml tag and put it on a var
                xmlDoc = document.getElementById('_formjAjaxRetornoXML');
             */
                //So we have a valid xml we can remove the xml tag document.body.removeChild(document.getElementById('_formjAjaxRetornoXML'));\n" +

            }
            else
            {
                //If the browser doesnt support xml
                alert('Your browser can not handle this script');
            }
            return xmlDoc;
    }

//Handle different situations of key pressing
 function onKeyDown(e, control)
 {
     var keynum
     var keychar
     var numcheck
     if(window.event) // IE
     {
         keynum = e.keyCode
     }
     else if(e.which) // Netscape/Firefox/Opera
     {
         keynum = e.which
     }

     keychar = String.fromCharCode(keynum)

     if (control=="quote")
     {
         if (keynum==13)
         {
             downloadStockQuote();
         }
    }
    else
    if (control=="login")
    {
         if (keynum==13)
         {
             signIN();
         }
   }
   else
   if (control=="stock_name")
   {
         if (keynum==13)
         {
             javascript:loadName();
         }
   }
 }

function copyToClipboard(value)
{
    var holdtext=document.getElementById("holdtext");
    holdtext.innerText = value;
    var Copied = holdtext.createTextRange();
    Copied.execCommand("Copy");
}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
/*
 * Add any function to be loaded after page is shown
 * http://www.webreference.com/programming/javascript/onloads/
 */
function addLoadEvent(func)
{
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function')
      {
	    window.onload = func;
	  }
      else
      {
	    window.onload = function()
        {
	      if (oldonload)
          {
	        oldonload();
	      }
	      func();
	    }
	  }
}
    function printNice(value)
    {
        //alert(value);
        var x =''+value;
        var sep=x.indexOf('.');
        var last_idx=x.length;

        if (sep==-1) {sep=last_idx;};
        var new_value='';
        while (sep>0)
        {
            var new_token=x.substring(Math.max(0,sep-3),sep);
            //alert(new_token);
            if (new_value!='')
            {
                new_value=new_token+','+new_value;
            }
            else
            {
                new_value=new_token;
            }
            sep=sep-3;
        }
        return new_value;
    }

 function setupDatePickers()
 {
     $('.input_date').datepicker({rangeSelect:    false,
    	                          closeText:      label_close,
	    						  clearText:      label_clear,
		    					  nextText:       label_next,
			    				  prevText:       label_prev ,
				    			  currentText:    label_current,
					    		  monthNames:     array_months,
						    	  dayNamesMin:    array_days,
							      showOn :        'both',
							      buttonImage:    'images/buttons/calendar.gif',
							      buttonImageOnly: true,
							      duration: '',
	                              firstDay: 1}).addClass("embed");

     $('.input_date25').datepicker({rangeSelect:    false,
                                   closeText:      label_close,
                                   clearText:      label_clear,
                                   nextText:       label_next,
                                   prevText:       label_prev ,
                                   currentText:    label_current,
                                   monthNames:     array_months,
                                   dayNamesMin:    array_days,
                                   showOn :        'both',
                                   buttonImage:    'images/buttons/calendar.gif',
                                   buttonImageOnly: true,
                                   duration: '',
                                   firstDay: 1}).addClass("embed");


    $("link[title=Flora (Default)]").attr("href", "css/jcalendar_datepicker_1.css");
 }

 //Check that value of the field is a normal URL
 function isValidURL(url)
 {
    var RegExp = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/; 
    if(RegExp.test(url))
    {
        return true;
    }
    else
    {
        return false;
    }
  }

//Check that value of the field is a normal email
function isValidEmail(email){
    var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/;
    if(RegExp.test(email)){
        return true;
    }else{
        return false;
    }
}

function ScrollToElement(theElement)
{

  var selectedPosX = 0;
  var selectedPosY = 0;

  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }

 window.scrollTo(selectedPosX,selectedPosY);

}

function getFormForAction(selectedFormName)
{
    var form = null;
    for (i=0;i<document.forms.length;i++)
    {
        var action=document.forms[i].action;
        if (action.indexOf(selectedFormName)!=-1)
        {
            form = document.forms[i];
            break;
        }

    }
    return form;
}


