﻿// trim
function trim(str)
{
	if (!str.match(/\S/))
		return ''
	str = str.replace(/^(\s*)(\S)(.*)$/,'$2$3') // trim left
	str = str.replace(/^(.*)(\S)(\s*)$/,'$1$2') // trim right
	return str
}

/*
 * preloading an image. creating an image object with given source
 * imgObj: name of object to be created
 * imgSrc: URL of image 
 */
function preload(imgObj,imgSrc)
{
	if (document.images) {
		eval(imgObj+' = new Image()');
		eval(imgObj+'.src = "'+imgSrc+'"');
    }
}

/*
 * change a layer's image elemnt's source
 * layer: name of a non nesting layer. if null look for image in document.images
 * imgName: name of image element
 * imgObj: name of preloaded image object
 * -> image element of layer source would be replaced with image object's source
 */
function changeImage(imgName,imgObj,layer)
{
    if (document.images) {
        if (document.all || document.getElementById || layer == null)
            eval('document.images["'+imgName+'"].src = '+imgObj+'.src');
        else eval('document.'+layer+'.document.images["'+imgName+'"].src = '+imgObj+'.src');
    }
}

/*
for void hrefs
*/
function nohref()
{
}


// parse file name from file's path
function getFileName(filePath)
{
    var p = Math.max(filePath.lastIndexOf('/'),filePath.lastIndexOf('\\'))
    return filePath.substring(p + 1,filePath.length)
}

// for each element correct the content text's html
// only ie & ns6+ compatible
function strToHtml()
{
    var i, textElm
    for (i = 1; ; i++) {
        if (document.all && !(textElm = document.all('html_text' + i)))
            break
        else if (document.getElementById && !(textElm = document.getElementById('html_text' + i)))
            break
        var txt = textElm.innerHTML
        txt = txt.replace(/&gt;/gi,'>')
        txt = txt.replace(/&lt;/gi,'<')
		txt = txt.replace(/&amp;/gi,'&')
        textElm.innerHTML = txt
    }
}

// html editor trim (trims non displayable html)
// for which case an html space is substitude by the following regular expression:
// space - [(\s)(&nbsp;)(<br>)(<p>&nbsp;<\/p>)]
// note case is ignored
function htmlTrim(html)
{
	if (!html.match(/[^(\s)(&nbsp;)(<br>)(<p>&nbsp;<\/p>)]/i))
        return ''
	html = html.replace(/^(\s|&nbsp;|<br>|<p>&nbsp;<\/p>)*([^(\s)(&nbsp;)(<br>)(<p>&nbsp;<\/p>)])(.*)$/i,'$2$3') // trim left
	html = html.replace(/^(.*)([^(\s)(&nbsp;)(<br>)(<p>&nbsp;<\/p>)])(\s|&nbsp;|<br>|<p>&nbsp;<\/p>)*$/i,'$1$2') // trim right
    return html
}

// This function opens a new window in the middle of the screen
// Parameters:
// w - the width of the window
// h - the height of the window
// ur - the URL of the window
// target - optional target of the window
function openwindow(w,h,ur,target)
{
	var winleft = screen.width/2 - ( w/2 )
	var wintop = screen.height/2 - ( h/2 ) - 30
	var params = "width=" +w + ",height=" + h + "," + "top=" + wintop + ",left=" + winleft +",scrollbars=yes,menubar=no,resizable=1,toolbar=no,location=no,status=yes"
	if (!target) target = ''
	var newWinObj = window.open(ur,target,params)
	if (newWinObj) newWinObj.focus()
}

// append an event handler
function eventAppend(eventHandler,handler)
{
	if (!eventHandler)
		return new Function(handler)
	var funcStr = eventHandler.toString()
	var p = funcStr.indexOf('{')+1
	var q = funcStr.lastIndexOf('}')-1
	funcStr = funcStr.substring(p,q) + ';' + handler
	return new Function(funcStr)
}

// return reference to an object.
// compatible with IE4 and above, NS6 and above
function getObjectById(id)
{
	if (document.all)
		return document.all(id)
	else if (document.getElementById)
		return document.getElementById(id)
	else
		return null
}

// display number with given precision
// returns a string
function precision(num,p)
{
	if (!p || isNaN(num) || num.length == 0)
		return num
	num *= Math.pow(10,p)
	num = Math.round(num)
	num = num*10 + 1
	num /= Math.pow(10,p+1)
	num = num.toString()
	num = num.substring(0,num.length-1)
	return num
}


//window.attachEvent('onload',function()
function loadFlashObject(html,targetObjId){
	window.getElementById(targetObjId).innerHTML = html;
}
function BrowserCheck()
{
	this.ns = (navigator.appName == "Netscape")
	this.ns4 = (document.layers)
	this.ns5 = (this.ns && navigator.appVersion.indexOf("5") != -1) // <==> ns 6.1 and above
	this.ie = (navigator.appName == "Microsoft Internet Explorer")
	this.ie4 = (!document.getElementById && document.all)
	this.ie5 = (navigator.appVersion.indexOf("MSIE 5.0") != -1)
	this.ie55 = (navigator.appVersion.indexOf("MSIE 5.5") != -1)
	this.ie6 = (navigator.appVersion.indexOf("MSIE 6.0") != -1)
	this.firefox = (navigator.userAgent.indexOf("Firefox")!=-1)
	if (this.ns)
		this.version = parseInt(navigator.appVersion)
	else if (this.ie)
		this.version = parseFloat(navigator.appVersion.split('MSIE')[1])
}
function addWindowLoadEvent(func){
	var browser = new BrowserCheck();
	
	if(browser.ns || browser.firefox)
		window.addEventListener("load",func,false);
	else
		window.attachEvent("onload",func);
}


/*PAGE BLOCKER FOR POPUP'S*/
var __Page = {};
__Page.ScreenPosition = function() {
    return document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
}
__Page.Center = function(obj) {
    var pos = {x:0, y:0};
    pos.x = ((document.body.offsetWidth-obj.offsetWidth)/2) + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    pos.y = 200 + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    if (pos.y < 35) pos.y = 35;
    pos.x -= 200;
    return pos;
}
__Page.Blocker = {};
__Page.Blocker.Show = function() {
    document.onselectstart = function() { event.returnValue = false; return false; }
    document.body.style.overflow = "hidden";
    var blocker = document.getElementById("blocker");
    if (!blocker) {
        blocker = document.body.appendChild(document.createElement("div"));
        blocker.className = "popupBlocker";
    }
    blocker.id = "blocker";
    blocker.style.display = "";
    blocker.style.top = __Page.ScreenPosition();
    blocker.style.width = document.body.offsetWidth;
    blocker.style.height = document.body.offsetHeight;
    
    //showHideSelect(true);
}
__Page.Blocker.Hide = function() {
    document.onselectstart = null;
    document.body.style.overflow = "auto";
    document.getElementById("blocker").style.display = "none";    
    
    //showHideSelect(false);
}
__Page.Blocker.LimitTabs = function(first, last) {
	first.focus();
	first.onkeydown = function() {
		if (event.keyCode == 9 && event.shiftKey) {
			event.returnValue = false;
			last.focus();
			return false;
		}
	}
	last.onkeydown = function() {
		if (event.keyCode == 9 && !event.shiftKey) {
			event.returnValue = false;
			first.focus();
			return false;
		}
	}
	document.getElementById("blocker").onclick = function() { first.focus(); }
}

function fixUrl(){
	if(document.location.href.toLowerCase().indexOf('bbm.co.il')>0 && document.location.href.toLowerCase.indexOf('www')<0) 
		var loc = document.location.href.split('http://');
		document.location.href = loc[0] + 'www/' + loc[1];
}
function createXmlHttpObject(){
	var xmlHttp;
	if(window.ActiveXObject)
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	else
		xmlHttp = new XMLHttpRequest();
	return xmlHttp;
}

function setSurveyVote(sid,rid){
	var answers = document.getElementsByName('poll' + sid);
	var answerId = -1;
	for(var i=0; i<answers.length; i++){
		if(answers[i].checked){
			answerId = answers[i].getAttribute('answerId');	
			break;
		}
	}
	
	var voteLabel = document.getElementById('voteLabel' + sid);
	
	if(answerId < 0){
		voteLabel.innerHTML = 'יש לסמן תשובה';
		return;
	}	
	
	voteLabel.innerHTML = 'מבצע רישום הצבעה, אנא המתן..';
	
	var xmlHttp = createXmlHttpObject();
	xmlHttp.open("GET", "/site/v2/survey/setAnswer.aspx?answerid=" + answerId);

	xmlHttp.onreadystatechange = function postVote(){
		if(xmlHttp.readyState != 4)return;

		var statusText = xmlHttp.responseText;
		//alert(statusText);
		voteLabel.innerHTML = 'הצבעתך נקלטה בהצלחה!';
		
		window.setTimeout(function(){
			voteLabel.innerHTML = 'מפנה לעמוד תוצאות סקרים. אנא המתן...'
			location.href = '/site/v2/survey/view.aspx?id='+sid;
		},1500);
	};
	xmlHttp.send();
}

function getNode(xmlDoc, elementPath)
{
    if(window.ActiveXObject)
    {
        return xmlDoc.selectSingleNode(elementPath);
    }
    else
    {
       var xpe = new XPathEvaluator();
       var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
       var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
       return results.singleNodeValue; 
    }
}
function getNodeText(xmlDoc, elementPath){
	var node = typeof elementPath == 'undefined' ? xmlDoc : getNode(xmlDoc, elementPath);
	if(node.textContent)
		return node.textContent;
	else
		return node.text;
}

//handle center banner closed
function hideCenterBanner(){
	//set 'isCenter' cookie value to false
	var banner = unescape(readCookie("banner"));
	var locations = banner.split('&');
	
	banner = banner.replace("isCenter=1","isCenter=0");
	createCookie("banner",escape(banner),1);
	
	//hide center banner								
	$("#trCenterBanner").hide();
	
	if(!_leftBanner || _leftBanner == '') return;
	
	//activate left banner (require scrolling)
	var soBanner = new SWFObject("/site/images/toptoolbar/banners/" + _leftBanner, "NavBarLeftBanner", "90", "550", "8", "#FFFFFF");
	
	soBanner.addParam("quality", "high");
	soBanner.write("LeftBannerContent");
	
	//animate the banner to the current scroll position:
	function animate(){																
		jQuery("#LeftBannerContent").animate({top: document.body.scrollTop},"slow","swing")
	}
	//activate a listener that chcecks when the scroll event has ended:
	function handleScroll() {
		if( interval == null)
			interval = window.setInterval(checkScroll,100);
	}
	var interval = null;
	var currTop = document.body.scrollTop;
	
	//check the scroll if it stoped
	function checkScroll(){
		if(currTop != document.body.scrollTop)
			currTop  = document.body.scrollTop;
		else{
			window.clearInterval(interval);
			interval = null;
			animate();
		}	
	}
	/* Initialization scroll check. */
	if (window.addEventListener)
		window.addEventListener('DOMMouseScroll', handleScroll, false);
	else
		window.onscroll = document.body.onscroll = handleScroll;		
}

//**cookie handle**//
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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
//create a document element and add it attributes
function createDocElement(elemType, attrStr){
	var elem = document.createElement(elemType)
	
	if(!attrStr)return elem
	
	var attributes = attrStr.split(',');	
	for(var i=0; i<attributes.length; i++){
		var nameValue = attributes[i].split('=');
		$(elem).attr(nameValue[0],nameValue[1]);
	}
	return elem;
}
function createCheckboxElement(checked, id){
	if($.browser.msie){
		var checkedAttr = checked ? "checked" : ""
		var checkbox = document.createElement("<input type='checkbox' "+ checkedAttr +"/>")
		checkbox.id = id
		return checkbox
	}else{
		var input = document.createElement("input")
		input.type = "checkbox"
		input.checked = checked
		input.id = id
		return input
	}
}