﻿if(!window.JSON)
	jQuery.getScript("/resources/bsb.controls/json2.js");

jQuery.log = function (message) { if (window.console) { console.debug(message); } else { /*alert(message);*/ } };
jQuery.parseFloat = function(value){
	return parseFloat(jQuery.customToFixed(value));
}

/*
test values

jQuery.parseFloat(2.9240000000000004)
jQuery.parseFloat(2.024)
jQuery.parseFloat(2.987)

jQuery.parseFloat(-2.9240000000000004)
jQuery.parseFloat(-2.024)
jQuery.parseFloat(-2.987)
jQuery.parseFloat(25.9999)
jQuery.parseFloat(1.6999999999999993)
jQuery.parseFloat(75*.023);
jQuery.parseFloat(26.125);
jQuery.parseFloat(34.123);
jQuery.parseFloat(78.439);
jQuery.parseFloat(12.498);
jQuery.parseFloat(9.016);
jQuery.parseFloat(37 * (2.8/100));

*/
jQuery.customToFixed = function (value) {
	if(value == "") return parseFloat(0).toFixed(2);
	if ((value + "").indexOf(".") < 0) return parseFloat(parseFloat(value)).toFixed(2);
	var isNegative = false;

	value = parseFloat(value);
	if(value < 0){
		isNegative = true;
		value = value * -1;
	}

	var strA = value + "";
	var decIndex = strA.indexOf(".");
	if (decIndex < 0) return (isNegative) ? parseFloat(value).toFixed(2) * -1 : parseFloat(value).toFixed(2);
	var baseVal = parseFloat(strA.substring(0, decIndex));
	var afterDesVal = strA.substring(decIndex + 1);

	if(afterDesVal.length <= 2) return (isNegative) ? parseFloat(value).toFixed(2) * -1 : parseFloat(value).toFixed(2);
	if((afterDesVal.length % 2) != 0) afterDesVal += "0";

	afterDesVal = afterDesVal.substring(0, 6); //handle only first 6 decimal

	var tt = afterDesVal;
	var totalNo = (afterDesVal.length/2);
	var goneExtra = 0;
	while(tt.length > 2){
		totalNo -= 1;
		var i = tt.length;
		var t = tt.substring(i-2, i);
		tt = tt.substring(0, i-2);

		var t1 = 0;
		if(parseFloat(t) >=50) t1 = 1;

		if(t1 > 0){
			if(parseFloat(tt) < 10){
				goneExtra = 0;
				tt = (parseFloat(tt) + 1) + "";
				if(tt.length%2 != 0) tt = "0" + tt;
			}else{
				tt = (parseFloat(tt) + 1) + "";
				if(tt.length%2 != 0)goneExtra = 1;
			}
		}
		tt = tt.substring(0, (totalNo*2) + goneExtra);
	}

	if(tt.length == 1) {
		baseVal++;
		tt = "0";
	}

	baseVal = baseVal + parseFloat("0." + tt);

	return (isNegative) ? parseFloat(baseVal).toFixed(2) * -1 : parseFloat(baseVal).toFixed(2);
};


(function ($) {
	$.fn.doRoundOff = function () {
		return this.each(doRoundOff);
	};

	$.fn.autoRoundOff = function () {
		return this.blur(doRoundOff);
	};

	function doRoundOff(){
		var tempVal = parseFloat($(this).val());
		if (isNaN(tempVal)) tempVal = 0;
		$(this).val($.customToFixed(tempVal));
	}
})(jQuery);

jQuery(document).ready(function(){
	jQuery(".resizeImage").each(function(){
		var resizeImg = this;
		resizeImg.onload = function(){
			$this = jQuery(this);
			var ratio = $this.width() / parseInt($this.attr("maxW"));
			ratio = Math.max(ratio, 1);
			$this.width( $this.width() / ratio );
			$this.height( $this.height() / ratio );
		};

		if(jQuery.browser.safari){
			resizeImg.safariTimer = window.setInterval(function(){
				if( resizeImg.complete ) {
					window.clearInterval(resizeImg.safariTimer);
					resizeImg.safariTimer = null;
					resizeImg.onload();
				}
			},100);
		}
	});
});

jQuery.fn.checkAll = function(containerSelector, controllerSelector){
        var controllerCnt = jQuery(controllerSelector)[0];

        jQuery(containerSelector).find("input[type='checkbox']").not(controllerCnt).each( function(){
            this.containerSelector = containerSelector;
            this.controllerSelector = controllerSelector;
            jQuery(this).live("click", function(){

				if( this.disabled ) return;
                if( this.checked == false ){
                    jQuery(this.controllerSelector).each(function(){this.checked = false});
                }
                else{
                    var allChecked = true;
                    jQuery(this.containerSelector).find("input[type='checkbox']").not(controllerCnt).each(function(){
                        if( this.checked === false ) allChecked = false;
                    });
					jQuery(this.controllerSelector).each(function(){this.checked = allChecked});
                }
            });
	    });

        jQuery(controllerSelector)
			.each(function(){
				this.containerSelector = containerSelector;
			})
			.live("click", function(){
				var controller = this;
				jQuery(this.containerSelector).find("input[type='checkbox']").not(controller).each(function(){
					if( this.disabled ) return;
					this.checked = controller.checked;
				});
			});

	    return this;
    };

jQuery(document).ready(function(){
	var focusSetDone = false;
	jQuery(".ValidOverride").each(function(){
		if(this.evaluationfunction){}else{return;}
		if(this.errormessage){}else{return;}
		var _originalValidationMethod = Function.createDelegate(this, this.evaluationfunction);
		this._validationMethodOverride = Function.createDelegate(this,
			function (val){
				var retVal = true;
				var errorMsg = this.errormessage;
				var currentMsg = "";
				var $ctl = jQuery("#" + this.controltovalidate);

				if(!_originalValidationMethod(val)) {
					val.isvalid = false;
					retVal = false;
				}

				var validators = $ctl[0].Validators;
				for(i=0; i< validators.length; i++){
					if(validators[i].isvalid == false){
						if (currentMsg.length > 0) currentMsg += "<br />";
						if(validators[i].errormessage)
							currentMsg += validators[i].errormessage ;
					}
				}

				$ctl.attr("currentErrorMsg", currentMsg);
				if(currentMsg.length > 0){
					$ctl.tipsy({trigger: 'manual', gravity: 'w', html: true});
					$ctl.tipsy("enable").tipsy("show", $ctl.attr("currentErrorMsg"));
				}else{
					try{
						$ctl.tipsy("hide");
					}catch(e){}
				}
				return retVal;
			}
		);

		if(this.isvalid === false){
			var $ctl = jQuery("#" + this.controltovalidate);
			$ctl.attr("currentErrorMsg", this.errormessage);
			$ctl.tipsy({title: function(){return $ctl.attr("currentErrorMsg");}, trigger: 'manual', gravity: 'w', html: true});
			$ctl.tipsy("show");
			if(focusSetDone == false){
				$ctl.focus();
				focusSetDone = true;
			}
		}
		this.evaluationfunction = this._validationMethodOverride;

	});
/* Chrome issue - checkbox, radobutton mouse click not maintain taborder it will moe focus to top of the page. */
	jQuery('input[type=checkbox]').click(function() {
	 jQuery(this).focus();
	});

	jQuery('input[type=radio]').click(function() {
	 jQuery(this).focus();
	});

});

function Page_ClientValidate(validationGroup) {
	Page_InvalidControlToBeFocused = null;
	if (typeof (Page_Validators) == "undefined") {
		return true;
	}
	var i;
	for (i = 0; i < Page_Validators.length; i++) {
		ValidatorValidate(Page_Validators[i], validationGroup, null);
	}
	ValidatorUpdateIsValid();
	ValidationSummaryOnSubmit(validationGroup);
	Page_BlockSubmit = !Page_IsValid;

	if (Page_BlockSubmit) {
		var setFocus = false;
		jQuery(".ValidOverride").each(function () {
			if (setFocus) return;
			if (this.isvalid === false) {
				jQuery("#" + this.controltovalidate).focus();
				setFocus = true;
				return;
			}
		});
	}
	return Page_IsValid;
}

/*
* jQuery.fn.textLimit( limit, callback );
*
* Add a limit to your textarea and inputfields.
*
* $('.element').textLimit( 100 );
*
* Version 1.0.0
* www.labs.skengdon.com/textLimit
* www.labs.skengdon.com/textLimit/js/textLimit.min.js
*/
; (function ($) { $.fn.clearTextLimit = function () { return this.each(function () { this.onkeydown = this.onkeyup = null; }); }; $.fn.textLimit = function (limit, callback) { if (typeof callback !== 'function') var callback = function () { }; return this.each(function () { this.limit = limit; this.callback = callback; this.onkeydown = this.onkeyup = function () { this.value = this.value.substr(0, this.limit); this.reached = this.limit - this.value.length; this.reached = (this.reached == 0) ? true : false; return this.callback(this.value.length, this.limit, this.reached); } }); }; })(jQuery);

$.extend({ URLEncode: function (c) {
	var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
	while (x < c.length) {
		var m = r.exec(c.substr(x));
		if (m != null && m.length > 1 && m[1] != '') {
			o += m[1]; x += m[1].length;
		} else {
			if (c[x] == ' ') o += '+'; else {
				var d = c.charCodeAt(x); var h = d.toString(16);
				o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
			} x++;
		}
	} return o;
},
	URLDecode: function (s) {
		var o = s; var binVal, t; var r = /(%[^%]{2})/;
		while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
			b = parseInt(m[1].substr(1), 16);
			t = String.fromCharCode(b); o = o.replace(m[1], t);
		} return o;
	}
});

function validateFacebookId(value) {
	return value.toLowerCase().indexOf("http://") < 0 && value.toLowerCase().indexOf("https://") < 0 && value.toLowerCase().indexOf("facebook.com") < 0;
};

function validateTwitterId(value,currentPortalId) {
	return value.toLowerCase().indexOf("http://") < 0 && value.toLowerCase().indexOf("https://") < 0 && value.toLowerCase().indexOf("twitter.com") < 0;
};
function validateInstagramId(value, currentPortalId) {
	return value.toLowerCase().indexOf("http://") < 0 && value.toLowerCase().indexOf("https://") < 0 && value.toLowerCase().indexOf("instagram.com") < 0;
};

function validateYoutubeId(value) {
	return value.toLowerCase().indexOf("http://") < 0 && value.toLowerCase().indexOf("https://") < 0 && value.toLowerCase().indexOf("youtube.com") < 0;
};

function validateFlickrId(value) {
	return value.toLowerCase().indexOf("http://") < 0 && value.toLowerCase().indexOf("https://") < 0 && value.toLowerCase().indexOf("flickr.com") < 0;
};

(function ($) {
	$.fn.doRoundOff = function () {
		return this.each(doRoundOff);
	};
	
	$.fn.longPageNav = function(){
		var $longPageNavHeader = $(this);
		var $longPageNavHeaderListHolder = $('<div class="pageJumpList"/>')
						.appendTo($longPageNavHeader)
						.width($longPageNavHeader.width());
		var start = $(longPageNavHeader).offset().top;
		var headerHeight = 0;

		var $ol = $("<ol type='1' class='pj-list'/>");
		$(".TeamPage_PPS_darkHeader").each(function(){
			var $this = $(this);
			var li = $("<li class='pj-item'/>").appendTo($ol);
			var a = $("<a class='pj-link' href='javascript:void(0)'/>").appendTo(li).html( $this.text());
			a[0].refElement = this;
		});

		$ol.appendTo($longPageNavHeaderListHolder);
		$longPageNavHeaderListHolder.append("<div style='clear:both' />");
		headerHeight = $longPageNavHeaderListHolder.outerHeight();
		$longPageNavHeader.height(headerHeight);

		$(window).scroll(function () {
			var p = $(window).scrollTop();
			$($longPageNavHeaderListHolder).css('position', ((p) > start) ? 'fixed' : 'static').css('top', ((p) > start) ? '0px' : '');
		});

		$("a", $longPageNavHeaderListHolder).click(function (e) {
			e.preventDefault();
			var $this = $(this);
			var offset = $(this.refElement).offset().top - (headerHeight + $this.height());
			$("html, body").animate({ scrollTop: offset }, 500);
		});
		
		return this;
	};

})(jQuery);