// jsr_class.js
//
// JSONscriptRequest -- a simple class for making HTTP requests
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//
//
// Sample Usage:
//
// <script type="text/javascript" src="jsr_class.js"></script>
// 
// function callbackfunc(jsonData) {
//      alert('Latitude = ' + jsonData.ResultSet.Result[0].Latitude + 
//            '  Longitude = ' + jsonData.ResultSet.Result[0].Longitude);
//      aObj.removeScriptTag();
// }
//
// request = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&
//            output=json&callback=callbackfunc&location=78704';
// aObj = new JSONscriptRequest(request);
// aObj.buildScriptTag();
// aObj.addScriptTag();
//
//


// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}



function ka_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 ka_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;
}

function ka_eraseCookie(name) {
	ka_createCookie(name,"",-1);
}

function ka_refresh_page(){
	window.location.href = window.location.href;
}

function ka_check_email(str){
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	   return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
	   return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	   return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
	   return false;
	}	
	if (str.indexOf(" ")!=-1){
	   return false;
	}
	return true;					
}

function ka_urldecode(str){
	return decodeURIComponent(str.replace(/\+/g,  " "));
}

function ka_urlencode(str){
	return encodeURIComponent(str);
}


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var ka_dtCh= "/";
var ka_minYear=1900;
var ka_maxYear=2100;

function ka_isInteger(s){
	var i=0;
    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 ka_stripCharsInBag(s, bag){
	var i=0;
    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 ka_daysInFebruary (yearCalc){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((yearCalc % 4 == 0) && ( (!(yearCalc % 100 == 0)) || (yearCalc % 400 == 0))) ? 29 : 28 );
}
function ka_DaysArray(nLocal) {
	for (var iLocal = 1; iLocal <= nLocal; iLocal++) {
		this[iLocal] = 31
		if (iLocal==4 || iLocal==6 || iLocal==9 || iLocal==11) {this[iLocal] = 30}
		if (iLocal==2) {this[iLocal] = 29}
   } 
   return this
}

function ka_isDateValidated(dtStr){
	var daysInMonthLocalArray = ka_DaysArray(12)
	var pos1=dtStr.indexOf(ka_dtCh)
	var pos2=dtStr.indexOf(ka_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)
	}
	var monthInt=parseInt(strMonth)
	var dayInt=parseInt(strDay)
	var yearInt=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || monthInt<1 || monthInt>12){
		//alert("Please enter a valid month")
		return false
	}

	//alert("Month days check:"+daysInMonthLocalArray[monthInt]);
	if (strDay.length<1 || dayInt<1 || dayInt>31 || (monthInt==2 && dayInt>ka_daysInFebruary(yearInt)) ){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || yearInt==0 || yearInt<ka_minYear || yearInt>ka_maxYear){
		//alert("Please enter a valid 4 digit year between "+ka_minYear+" and "+ka_maxYear)
		return false
	}
	if (dtStr.indexOf(ka_dtCh,pos2+1)!=-1 || ka_isInteger(ka_stripCharsInBag(dtStr, ka_dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

function ka_isOver13(bmonth, bday,byear){
		var propVal = 13;
                bday = bday == "Select" ? 0 : parseInt(bday);
                bmonth = bmonth == "Select" ? 0 : parseInt(bmonth) - 1;
                byear = byear == "Select" ? 0 : parseInt(byear);
                var now = new Date();
                cday = now.getDate();
                cmonth = now.getMonth();
                cyear = now.getFullYear();
                if ((cmonth > bmonth) || (cmonth == bmonth && cday >= bday)) {
                    var age = byear;
                    age = cyear - age;
                } else {
                    var age = byear + 1;
                    age = cyear - age;
                }
                return (age >= propVal ? true: false);

}

function ka_echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	   // alert("Invalid E-mail ID")
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	   // alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	   // alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	   // alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.indexOf(" ")!=-1){
	   // alert("Invalid E-mail ID")
	    return false
	 }

	 return true					
}

function ka_ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }

function ka_getUrlValue(name){
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}


function ka_trim(str){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');	
}

function ka_friendlyURL(str){
    str = ka_trim(str);

    /** Things to replace with underscore **/
    str = str.replace(/[\s,.'|+]/g, "-");
    
    /** Things to replace with nothing **/
    str = str.replace(/[:|;|"|'|-|,|.|\/|\\|\<|\>]/g, "");

    str = str.toLowerCase();
    
	//remove multiple dashes
	var intIndexOfMatch = str.indexOf('--');
	while (intIndexOfMatch != -1){
	  str = str.replace('--', '-');
	  intIndexOfMatch = str.indexOf('--');
	}	
    
    return str;
}

function ka_stripHTML(str){
	var str = new String(str); 
	//alert(str);
	
	str = str.replace(/&nbsp;/g, ' ');
	str = str.replace(/\t/g, ' ');
	str = str.replace(/ /g, ' ');
	str = str.replace(/<.*?>/g, ' ');

	//remove multiple spaces
	var intIndexOfMatch = str.indexOf('  ');
	while (intIndexOfMatch != -1){
	  str = str.replace('  ', ' ');
	  intIndexOfMatch = str.indexOf('  ');
	}	
	
	str = ka_trim(str);
	
	//alert(str);
	return str;
}

(function($) {
    $.scrollToElement = function( $element, speed ) {

        speed = speed || 750;

        $("html, body").animate({
            scrollTop: $element.offset().top,
            scrollLeft: $element.offset().left
        }, speed);
        return $element;
    };

    $.fn.scrollTo = function( speed ) {
        speed = speed || "normal";
        return $.scrollToElement( this, speed );
    };
})(jQuery);

