var isCO = 'false';

//attach a window event:
function addWindowEvent(eventName, handler, sender) {
    try {
        if (navigator.appName == "Microsoft Internet Explorer" || document.all)
            window.attachEvent(eventName, handler);
        else {
        
            eventName = eventName.replace('on', '');
            window.addEventListener(eventName, handler, false);
        }
    }
    catch (e) {
        //alert(sender);
    }
} 
//alert('common ' + window.location.toString().toLowerCase())
var Constants = {
		isIE : navigator.appName.toLowerCase().indexOf("explorer") > -1,
		isMoz : !this.isIE,
		mode : "prod"
}
function trim(str)
{
	return str.replace(/^\s{1,}/ig, "").replace(/\s{1,}$/ig, "");
}

//Gives 100% height to the inner_content
function setContentHeight(){
	var windowHeight = getWindowHeight();
	var contentHeight = getInnerContent().offsetHeight;
	if (contentHeight < windowHeight){
    getInnerContent().style.height = windowHeight - 180  + "px";
  }
}

function getWindowHeight(){
	windowHeight = (document.all) ? document.documentElement.offsetHeight-4 : document.documentElement.scrollHeight;
	return windowHeight;
}

function getInnerContent(){
	try{
		return document.getElementById("inner_content");
	}
	catch(err){
		var divs = document.getElementsByTagName("div");
		for (i=0; i<divs.length; i++){
			if (divs[i].className=="inner_content")
				return divs[i];
		}
	}
}

//Clears predefined text from textfield
function clearText(element, value){
    if (element.value==value){//If the value of the textfield equals the predefined text
        element.value="";//Clear the textfield
    }
}	

//Fills predefined text into textfield
function fillText(element, value){
    if (element.value==""){//If the value of the textfield is empty
        element.value=value;//Fill the textfield
    }
    
}

// getting text from node depends on browser
function getTextFromNode(node)
{
	if(Constants.isIE)
		return node.text
	else if (Constants.isMoz)
		return node.childNodes[0].nodeValue
}

function isNullOrUndefined(obj)
{
    try
    {
        return ((obj == null) || (obj == undefined) || (typeof (obj) == "undefined") || (obj == "null"));
	}
	catch(e)
	{
	    return true;
	}    
}

function notNullOrUndefined(obj)
{
	return !isNullOrUndefined(obj)
}

function nvl(strObj, alternate)
{
    if (isNullOrUndefined(strObj))
        return alternate
    else
        return strObj
}
/* mock up functions */
/* Generel Loading Functions */
function drawEllipsis() {
	var ellipsisObj = document.getElementsByName('ellipsis');
	for (var i=0; i<ellipsisObj.length; i++) {
		handleEllipsis(ellipsisObj[i]);
	}
}

function drawButtons() {
	var buttonObj = document.getElementsByName('button');
	for (var i=0; i<buttonObj.length; i++) {
		buttonObj[i].onmouseover = function() {			
			this.style.backgroundImage = (document.all) ? this.currentStyle.backgroundImage.replace('.gif', '_over.gif') : window.getComputedStyle(this, null).backgroundImage.replace('.gif', '_over.gif');
		}

		buttonObj[i].onmouseout = function() {
			this.style.backgroundImage = (document.all) ? this.currentStyle.backgroundImage.replace('_over.gif', '.gif') : window.getComputedStyle(this, null).backgroundImage.replace('_over.gif', '.gif');
		}

		buttonObj[i].onmousedown = function() {
			this.style.backgroundImage = (document.all) ? this.currentStyle.backgroundImage.replace('_over.gif', '_press.gif') : window.getComputedStyle(this, null).backgroundImage.replace('_over.gif', '_press.gif');
		}

		buttonObj[i].onmouseup = function() {
			this.style.backgroundImage = (document.all) ? this.currentStyle.backgroundImage.replace('_press.gif', '_over.gif') : window.getComputedStyle(this, null).backgroundImage.replace('_press.gif', '_over.gif');
		}
	}
}

/*function hidePopups() {

var popupsObj = document.getElementById('popups');
	if(popupsObj != null) {
	    for (var i=0; i<popupsObj.childNodes.length; i++) {
		    if (popupsObj.childNodes[i].tagName == "DIV") {
			    popupsObj.childNodes[i].style.display = 'none';
			   
		    }	
	    }
	}
}*/

function hidePopups() {
   var popupsObj = document.getElementById('popups');
	for (var i=0; i<popupsObj.childNodes.length; i++) {
		if (popupsObj.childNodes[i].tagName == "DIV") {
			popupsObj.childNodes[i].style.display = 'none';
		}	
	}
}

function toggleSeeAllLink(elementCount){
    var seeAllLink = document.getElementById("seeAllLink"+elementCount);
    
    if (seeAllLink.innerHTML == '...')
        seeAllLink.innerHTML = "See more...";
    else
        seeAllLink.innerHTML = "...";
}

function handleEllipsis(ellipsisObj) {

	var objWidth = (document.all) ? parseInt(ellipsisObj.currentStyle.width) : parseInt(window.getComputedStyle(ellipsisObj, null).width);
	var objHeight = (document.all) ? parseInt(ellipsisObj.currentStyle.height) : parseInt(window.getComputedStyle(ellipsisObj, null).height);
	
	if (ellipsisObj.className.indexOf("2line") != -1 ||
	    ellipsisObj.className.indexOf("3line") != -1) {
		var condition = ellipsisObj.scrollWidth > objWidth || ellipsisObj.scrollHeight > objHeight;
	} else {
		var condition = ellipsisObj.scrollWidth > objWidth;
	}
////
    //if(document.getElementById('blowupDescription')==ellipsisObj)
    //alert(ellipsisObj.scrollWidth + "==" + objWidth)
	if (condition) {
		var left = ellipsisObj.offsetWidth-10+'px';

		var ellipsisTypes = new Array();
		ellipsisTypes['nowPlaying'] = 'left:'+left+'; background-color:#C1DAFD;';
		ellipsisTypes['related'] = 'left:'+left+'; background-color:#F5F4F0;';
		ellipsisTypes['related2Lines'] = 'left:'+left+'; background-color:#F5F4F0; padding-top:16px;';
		ellipsisTypes['thumbnail'] = 'left:'+left+'; background-color:#fff; padding-top:4px;';
		ellipsisTypes['credits'] = 'left:'+left+'; background-color:#fff;';
		ellipsisTypes['blowupTitle'] = 'left:'+left+'; background-color:#BAD6FD;';
		ellipsisTypes['blowup2Lines'] = 'left:'+left+'; background-color:#fff; padding-top:16px;';
		ellipsisTypes['blowup'] = 'left:'+left+'; background-color:#fff;';
		ellipsisTypes['blowupHits'] = 'left:'+left+'; background-color:#fff;';
		ellipsisTypes['commentTitle'] = 'left:'+left+'; background-color:#EBE7DF;';
		ellipsisTypes['flagTitle'] = 'left:'+left+'; background-color:#F2F1EC; padding-top:1px;';
		ellipsisTypes['winners'] = 'left:'+left+'; background-color:#FFF8DE;';
		ellipsisTypes['leftSlider'] = 'left:'+left+'; background-color:#E9F2FE; padding-top:14px;';

		ellipsisTypes['default'] = 'left:'+left+'; background-color:#fff;';

		// Show Ellipsis Dots
		var div = document.createElement("div");
		div.className = "ellipsis_dots";
		div.innerHTML = "...";
  
		div.style.cssText = (ellipsisObj.attributes["ellipsisType"] == undefined) ? ellipsisTypes['default'] : ellipsisTypes[ellipsisObj.attributes["ellipsisType"].value];

		ellipsisObj.className += ' ellipsis';
		ellipsisObj.appendChild(div);

		// Show Ellipsis Baloon
		ellipsisObj.onmouseover = function() {
			if (this.textContent) {
				var titleText = this.textContent.substring(0, this.textContent.length-3);
			} else {
				var titleText = this.innerText.substring(0, this.innerText.length-3);
			}
			this.title = titleText;
			//document.getElementById('ellipsisTitle').innerHTML = titleText;
			//document.getElementById('ellipsisTitle').style.display = '';
		}

		ellipsisObj.onmouseout = function() {
			//document.getElementById('ellipsisTitle').style.display = 'none';
		}
	}
}

//Clears predefined text from textfield
function clearText(element, value){
    if (element.value==value){//If the value of the textfield equals the predefined text
        element.value="";//Clear the textfield
    }
}

//Fills predefined text into textfield
function fillText(element, value){
    if (element.value==""){//If the value of the textfield is empty
        element.value=value;//Fill the textfield
    }
}

//Rename a sets name
function renameSet(setTopID, action){//gets the wrapping box's ID and the action requested ("start"/"end")
    var setTop = document.getElementById(setTopID);//gets the wrapping element
    
    //takes all the A elements and sets them into variables
    var setTopAnchors = setTop.getElementsByTagName("A");
    for (i=0; i<setTopAnchors.length; i++){
        if (setTopAnchors[i].className=="lnk_animation_name"){
           var lnk_animation_name = setTopAnchors[i];
           var em = lnk_animation_name.getElementsByTagName("EM")[0];
        }
        if (setTopAnchors[i].className=="lnk_rename")
           var lnk_rename = setTopAnchors[i];
        if (setTopAnchors[i].className=="lnk_delete")
           var lnk_delete = setTopAnchors[i];
    }
    
     //takes all the INPUT elements and sets them into variables
    var setTopInputs = setTop.getElementsByTagName("INPUT");
    for (i=0; i<setTopInputs.length; i++){
        if (setTopInputs[i].className=="input_animation_name")
           var input_animation_name = setTopInputs[i];
    }
    
    if (action=="start"){//("Rename" was pressed)
    
        setTop.className = returnAttr(setTop.className, "normal", "edit");//Changes "min_box_top normal" to "min_box_top edit"
        //input_animation_name.select();//Selects the text inside the textfield
        //alert(setTop.className);
        input_animation_name.focus();//focus's on it
    }
    else{ //action=="end" ("Save was pressed")
        setTop.className = returnAttr(setTop.className, "normal", "edit");//Changes "min_box_top edit" to "min_box_top normal"
        lnk_animation_name.innerHTML = input_animation_name.value;//Sets the value of the title to whatever was inserted in the textfield
         // update the db
        updateText = input_animation_name.value;
        // take the first 20 letters
        updateText = updateText.substring(0,20);
        // save the new name in the db
        updateSetID = setTop.id.split("_")[4];
        var urlUpdate = appPathScript+ "/Pages/Application/Animations/QuickServices.aspx";
      
        params = "action=updatesetname&setID="+updateSetID+
			"&setName="+updateText+"&setType="+mode;
        AJAX.asyncWithCallback(urlUpdate, params, "", true, false) ;
    }    
}

//Replaces an elements attribute with another
function returnAttr(attribute, value1, value2){
    if (attribute.indexOf(value1)!=-1)//If the attribute value already has value1 in it
        return attribute.replace(value1, value2);//exchange them
    else//If the attribute value does not have value1 in it (meaning it has value2)
        return attribute.replace(value2, value1);//exchange them
}

//Toggles btn_expand_all's label ("Expand all"/"Collapse all") 
function toggleExpandAllButton(wrapperID){
    var wrapper = document.getElementById(wrapperID);//sets the element
    var divs = wrapper.getElementsByTagName("DIV");//Takes all the DIV elements
    //var btn_expand_all = document.getElementById("btn_favorites_expand_all");//sets the element
    
    var minimizedFlag = false;
    for (i=0; i<divs.length; i++){//Runs through them
        if (divs[i].className.indexOf("minimized")!=-1){//If the element class name has "minimized" in it
            minimizedFlag = true;
        }
    }
    var hrefs = wrapper.getElementsByTagName("A");
    for (i=0; i<hrefs.length; i++){//Runs through them
        if (hrefs[i].className=="btn_expand_all"){
            var btn_expand_all = hrefs[i];
        }
    }
    if (minimizedFlag != true)
        btn_expand_all.innerHTML = "Collapse all";
    else
        btn_expand_all.innerHTML = "Expand all";
}

//Expands/collapse all sets within an element
function toggleAllSets(wrapperID , btn){
    btn = document.getElementById(btn);
    var wrapper = document.getElementById(wrapperID);//sets the element
    var divs = wrapper.getElementsByTagName("DIV");//Takes all the DIV elements
    for (i=0; i<divs.length; i++){//Runs through them
        if (divs[i].className.indexOf(returnAction(btn))!=-1){//If the element class name has "minimized" in it
            elementCount = divs[i].id.split("_")[3];//Takes the number at the end of its ID (e.g. mini_box_3)
            var insideDivs = divs[i].getElementsByTagName("DIV");//Takes all it's divs
            for (j=0; j<insideDivs.length; j++){//Runs through them
               if (insideDivs[j].className=="minimizable_box_bottom"){//If the element class name is "minimizable_box_bottom"
                    effect("toggle", wrapperID, elementCount)//Expand it
                } 
            }
        }
    }
}

//Meant to serve toggleAllSets function
//Depending on the btn_expand_all label ("Expand all"/"Collapse all") it returns a string ("expanded"/"minimized")
function returnAction(button){
    if (button.innerHTML == "Collapse all")
        return "expanded";
    else
        return "minimized";
}

////Creates an effect. Taken from script.aculo.us
//function effect(effect, wrapperId, elementCount){
//    switch (effect){//toggle/blindDown/Appear...
//        case "toggle":
//            switch (wrapperId){
//                case "movies_box1":
//                    var mini_box = 'mini_movies_box_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
//                    var mini_box_bottom = 'mini_movies_box_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
//                    var mini_box_top = 'mini_movies_box_top_'+elementCount; mini_box_top = document.getElementById(mini_box_top);//Sets the wrapper element in order to give it a border
//                    
//                    //Blinds up/down then toggles className
//                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded");toggleExpandAllButton(wrapperId)}});
//                    break;
//                case "favorites_box1":
//                    var mini_box = 'mini_favorites_box_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
//                    var mini_box_bottom = 'mini_favorites_box_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
//                    var mini_box_top = 'mini_favorites_box_top_'+elementCount; mini_box_top = document.getElementById(mini_box_top);//Sets the wrapper element in order to give it a border
//                    
//                    //Blinds up/down then toggles className
//                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded");toggleExpandAllButton(wrapperId)}});
//                    break;
//                case "box3":
//                    var mini_box_bottom = 'mini_box3_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
//                    var mini_box = 'mini_box3_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
//                    //Hides the red tooltip or else it stays in place and looks unproffesional
//                    try{
//                        hideTooltip()
//                    }
//                    catch(err){}
//                    
//                    //Blinds up/down then toggles className
//                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
//                    break;
//                case "box3 contest":
//                    var mini_box_bottom = 'mini_box3_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
//                    var mini_box = 'mini_box3_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
//                    
//                    //Blinds up/down then toggles className
//                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
//                    break;
//                case "box4":
//                    var mini_box_bottom = 'mini_box4_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
//                    var mini_box = 'mini_box4_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
//                    hideTooltip();//Hides the red tooltip or else it stays in place and looks unproffesional
//                    
//                    //Blinds up/down then toggles className
//                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
//                    break;
//            }
//            break;
//    }
//}

//Creates an effect. Taken from script.aculo.us
function effect(effect, wrapperId, elementCount, noExpandAll){
   switch (effect){//toggle/blindDown/Appear...
        case "toggle":
            switch (wrapperId){
                case "categories_box":
                    var mini_box = 'mini_movies_box_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    var mini_box_bottom = 'mini_movies_box_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box_top = 'mini_movies_box_top_'+elementCount; mini_box_top = document.getElementById(mini_box_top);//Sets the wrapper element in order to give it a border
                    
                    //Blinds up/down then toggles className                    
					new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded");}});
                    break;            
                case "movies_box1":
                    var mini_box = 'mini_movies_box_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    var mini_box_bottom = 'mini_movies_box_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box_top = 'mini_movies_box_top_'+elementCount; mini_box_top = document.getElementById(mini_box_top);//Sets the wrapper element in order to give it a border
                    
                    //Blinds up/down then toggles className
					new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded");toggleExpandAllButton(wrapperId)}});
                    break;
                case "favorites_box1":
                    var mini_box = 'mini_favorites_box_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    var mini_box_bottom = 'mini_favorites_box_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box_top = 'mini_favorites_box_top_'+elementCount; mini_box_top = document.getElementById(mini_box_top);//Sets the wrapper element in order to give it a border
                    
                    //Blinds up/down then toggles className
                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded");toggleExpandAllButton(wrapperId)}});
                    break;
                case "box3":
                    var mini_box_bottom = 'mini_box3_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box = 'mini_box3_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    //Hides the red tooltip or else it stays in place and looks unproffesional
                    try{
                        hideTooltip()
                    }
                    catch(err){}
                    
                    //Blinds up/down then toggles className
                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
                    break;
                case "box3 contest":
                    var mini_box_bottom = 'mini_box3_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box = 'mini_box3_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    
                    //Blinds up/down then toggles className
                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
                    break;
                case "box4":
                    var mini_box_bottom = 'mini_box4_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box = 'mini_box4_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    hideTooltip();//Hides the red tooltip or else it stays in place and looks unproffesional
                    
                    //Blinds up/down then toggles className
                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
                    break;
                case "box31":
                    var mini_box_bottom = 'mini_box31_bottom_'+elementCount;//Sets the ID of the "mini_box_bottom" that the effect will work on
                    var mini_box = 'mini_box31_'+elementCount; mini_box = document.getElementById(mini_box);//Sets the wrapper element in order to switch its class name
                    hideTooltip();//Hides the red tooltip or else it stays in place and looks unproffesional
                    
                    //Blinds up/down then toggles className
                    new Effect.toggle(mini_box_bottom, 'blind', {duration:0.2, afterFinish: function() {mini_box.className = returnAttr(mini_box.className, "minimized", "expanded")}});
                    break;

            }
            break;
    }
}
/* TOOLTIP **************************************************************************/
/************************************************************************************/

/**/function enableTooltip(wrapperID){
/**/    var links,i,h;
/**/    if(!document.getElementById || !document.getElementsByTagName) return;
/**/    h=document.createElement("span");
/**/    h.id="btc";
/**/    h.setAttribute("id","btc");
/**/    h.style.position="absolute";
/**/    h.style.zIndex=100;
/**/    document.getElementsByTagName("body")[0].appendChild(h);
/**/    if(wrapperID==null) links=document.getElementsByTagName("a");
/**/    else links=document.getElementById(wrapperID).getElementsByTagName("a");
/**/    for(i=0;i<links.length;i++){
/**/        if (links[i].className=="lnk_tooltip")
/**/            Prepare(links[i]);
/**/    }
/**/}
/**/    
/**/function Prepare(el){
/**/    var tooltip,b,s,l,close,clearer;
/**/    el.RemoveAttribute("href");
/**/    tooltip=CreateEl("span","tooltip");
/**/    s=CreateEl("SPAN","tooltip_top");
/**/    tooltip.appendChild(s);
/**/    l=CreateEl("SPAN","tooltip_content");
/**/    l.innerHTML="The movie has been uploaded to our servers and is being encoded. This may take a while.<br /> In the meantime you can watch other movies or do whatever you want to.";
/**/    tooltip.appendChild(l);
/**/    b=CreateEl("SPAN","tooltip_bottom");
/**/    tooltip.appendChild(b);
/**/
/**/    el.tooltip=tooltip;
/**/    el.onclick=showTooltip;
/**/    tooltip.onclick=hideTooltip;
/**/}
/**/
/**/function showTooltip(e){
/**/    var toolTipsArray = document.getElementsByTagName("span");
/**/    for(i=0;i<toolTipsArray.length;i++){
/**/        if (toolTipsArray[i].id=="btc"){
/**/            if(toolTipsArray[i].childNodes.length>0) toolTipsArray[i].RemoveChild(toolTipsArray[i].firstChild);
/**/        }
/**/    }
/**/    document.getElementById("btc").appendChild(this.tooltip);
/**/    Locate(e);
/**/}
/**/
/**/function hideTooltip(e){
/**/    var d=document.getElementById("btc");
/**/    if(d.childNodes.length>0) d.RemoveChild(d.firstChild);      
/**/}
/**/
/**/function CreateEl(t,c){
/**/    var x=document.createElement(t);
/**/    x.className=c;
/**/    x.style.display="block";
/**/    return(x);
/**/}
/**/function Locate(e){
/**/    var posx=0,posy=0;
/**/    if(e==null) e=window.event;
/**/    if(e.pageX || e.pageY){
/**/        posx=e.pageX; posy=e.pageY;
/**/        }
/**/    else if(e.clientX || e.clientY){
/**/        if(document.documentElement.scrollTop){
/**/            posx=e.clientX+document.documentElement.scrollLeft;
/**/            posy=e.clientY+document.documentElement.scrollTop;
/**/        }
/**/        else{
/**/            posx=e.clientX+document.body.scrollLeft;
/**/            posy=e.clientY+document.body.scrollTop;
/**/        }
/**/    }
/**/    document.getElementById("btc").style.top=(posy-100)+"px";
/**/    document.getElementById("btc").style.left=(posx+10)+"px";
/**/}
/**/
/* TOOLTIP END **************************************************************************/
/************************************************************************************/

function deleteSet(setID){
    alert("Not Implemented");
}


/* BLOCKER and POPUP */
/* this function is being invoked when the delete animation is called */
function showPopup(content){	
	document.body.scroll = "no";
   containerHeight = (document.all) ? document.documentElement.offsetHeight-4 : document.documentElement.scrollHeight;
	bodyHeight = window.document.body.offsetHeight;
	currentHeight = 0;

	if (containerHeight < bodyHeight){
		currentHeight = bodyHeight;
	}
	else{
		currentHeight = containerHeight;
	}

	document.getElementById("blocker").style.height = currentHeight + "px";
	toggleBlocker("show", content);
}

function createAniboomPopup(content){//alert(content)
    content = document.getElementById(content); 
    //alert(content)
    content.style.display = '';
    var width=content.style.width;
        width = width.replace("px","");
        width = width-0+10+10;//adding the 10px borders from both sides
    
    var clear=document.createElement("div");
        clear.className="clear";
    
    var pw = document.createElement("div");
        pw.setAttribute("id","popup_wrapper");
        document.getElementsByTagName("body")[0].appendChild(pw);
    
    var p=document.createElement("div");
        p.setAttribute("id","popup");
        p.style.width=width + "px";
        p.style.position="absolute";
        p.style.left="-"+(width/2)+"px";
        pw.appendChild(p);
    
    var pt=document.createElement("div");
        pt.className="popup_top";
        p.appendChild(pt);
    
    var ptlc=document.createElement("div");
        ptlc.className="top_left_corner";
        pt.appendChild(ptlc);
    var ptf=document.createElement("div");
        ptf.className="top_fill";
        ptf.style.width=(width-7-7) + "px";
        pt.appendChild(ptf);
    var ptrc=document.createElement("div");
        ptrc.className="top_right_corner";
        pt.appendChild(ptrc);
        pt.appendChild(clear);
    
    p.appendChild(content);
        content.style.width = width-10-10+"px";//borders are 10px each
    
       
    var pb=document.createElement("div");
        pb.className="popup_bottom";
        p.appendChild(pb);
    
    var pblc=document.createElement("div");
        pblc.className="bottom_left_corner";
        pb.appendChild(pblc);
    var pbf=document.createElement("div");
        pbf.className="bottom_fill";
        pbf.style.width=(width-18-18) + "px";
        pb.appendChild(pbf);
    var pbrc=document.createElement("div");
        pbrc.className="bottom_right_corner";
        pb.appendChild(pbrc);
        pb.appendChild(clear);   
    
    /************/
    var ps=document.createElement("div");
        ps.setAttribute("id","popup_shadow");
        ps.style.width=width + "px";
        ps.style.position="absolute";
        ps.style.left="-"+(width/2+7)+"px";
        pw.appendChild(ps);
    
    var pst=document.createElement("div");
        pst.className="popup_top";
        ps.appendChild(pst);
    
    var pstlc=document.createElement("div");
        pstlc.className="top_left_corner";
        pst.appendChild(pstlc);
    var pstf=document.createElement("div");
        pstf.className="top_fill";
        pstf.style.width=(width-7) + "px";
        pst.appendChild(pstf);
        pst.appendChild(clear);
    
    var pspc=document.createElement("div");
        pspc.className="popup_content";
        pspc.style.height = (content.offsetHeight+10)+"px";
        ps.appendChild(pspc);
    
    var psb=document.createElement("div");
        psb.className="popup_bottom";
        ps.appendChild(psb);
    
    var psblc=document.createElement("div");
        psblc.className="bottom_left_corner";
        psb.appendChild(psblc);
    var psbf=document.createElement("div");
        psbf.className="bottom_fill";
        psbf.style.width=(width-7-7) + "px";
        psb.appendChild(psbf);
    var psbrc=document.createElement("div");
        psbrc.className="bottom_right_corner";
        psb.appendChild(psbrc);
        psb.appendChild(clear);  
    
    p.style.top="-"+(p.offsetHeight/2)+"px"; 
    ps.style.top="-"+(ps.offsetHeight/2-7)+"px"; 
    togglePopup(pw, "show", 1);//the "1" is the contentID that ain't needed for the "show" action
   
}

function togglePopup(pw, action, contentID){
    if (action=="show"){
       new Effect.Opacity(
            pw,
            {
                duration: 0.2,
                from:0.0,
                to:1.0
            }
       );
    }
    else{
        new Effect.Opacity(
            pw,
            {
                duration: 0.2,
                from:1.0,
                to:0.0,
                afterFinish : function(){                	
                    var content = document.getElementById(contentID);
                    content.style.display = 'none';
                    document.getElementsByTagName("body")[0].appendChild(content);                    
                    var popup_wrapper = document.getElementById("popup_wrapper");
                    document.getElementsByTagName("body")[0].RemoveChild(popup_wrapper);                    
                    toggleBlocker("hide");                    
                }
            }
       );
    }
}

function hidePopup(contentID){	
		document.body.scroll = "yes";
    var popup_wrapper = document.getElementById("popup_wrapper");
    togglePopup(popup_wrapper, "hide", contentID);
}

function toggleTab(currentTab, futureTab){
    if (futureTab!="statistics"){
        var inner_content =  document.getElementById("inner_content");
        inner_content.className = returnAttr(inner_content.className, currentTab, futureTab);
    }
}

function toggleBlocker(action, content){
    var blocker = document.getElementById("blocker");
    if (action == "show"){
        blocker.style.display="block";
        new Effect.Opacity(
            blocker,
            {
                duration: 0.2,
                from:0.0,
                to:0.8,
                afterFinish : function(){
                    createAniboomPopup(content)
                }
            }
       );
    }
    else{
        new Effect.Opacity(
            blocker,
            {
                duration: 0.2,
                from:0.8,
                to:0.0,
                afterFinish : function(){
                    blocker.style.display="none";
                }
            }
       );
    }
}

/* Custom popup */
function showCustomPopup(popupId, popupTitle, popupText, buttonArr, popupWidth){
		if (document.getElementById(popupId)){
				//alert("");
			}
			var pc=document.createElement("div");
					pc.className="popup_content";
					pc.id=popupId;
					
					var h1=document.createElement("H1");
						pc.appendChild(h1);
					var bpc=document.createElement("A");	
						h1.appendChild(bpc);
						bpc.className="btn_popup_close";
						bpc.setAttribute("href","javascript:hidePopup('"+popupId+"')");
					var title=document.createTextNode(popupTitle);
						h1.appendChild(title);
					var para= document.createElement("P");
						pc.appendChild(para);
					var pt=document.createTextNode(popupText);
						para.appendChild(pt);
					var btns= document.createElement("P");
						pc.appendChild(btns);
					var btns= document.createElement("P");
						pc.appendChild(btns);
						btns.className="buttons";
					var sClear=document.createElement("SPAN");
						btns.appendChild(sClear);
						sClear.className="clear";
											
					document.body.appendChild(pc);
			pc.style.width=popupWidth+"px";
			title.nodeValue = popupTitle;
			pt.nodeValue = popupText;
	
			for (i=0; i<buttonArr.length; i++){
				buttonType = buttonArr[i].split(",")[0];
				buttonFunc = buttonArr[i].split(",")[1];
				
				buttonArr[i] = document.createElement("A");
				btns.appendChild(buttonArr[i]);
				buttonArr[i].setAttribute("href","javascript:" + buttonFunc);
				buttonArr[i].className="btn_popup_" + buttonType;
			}

			showPopup(popupId);
			
}

//Happens in #related_stretch_beige
//When clicking a link the below content changes and the selected link becomes non-active
function toggleLinkActivation(clickedLink){
    if (clickedLink.className.indexOf("selected")!=-1) return false; //If the link was clicked although it was selected - do nothing and get the hell out of the function
    
    var selectedLink;
    //Finds the currently selected link and turn it into a regular one        
    var anchors = document.getElementsByTagName("a");
    for (i=0; i<anchors.length; i++){
        if (anchors[i].className.indexOf("reg_link")!=-1){ //If the link has the class "reg_link" or "reg_link_small"
            if (anchors[i].className.indexOf("selected")!=-1){//If it's selected
                selectedLink = anchors[i];
                selectedLink.style.textDecoration="none"; //Fixes an underline bug in IE
                break;
            }
        }
    }
    
    var selectedLinkParent = selectedLink.parentNode;// Sets the parentNode and will be used if its "related_subcontent_text reg_text_small"
    
    /*if (selectedLinkParent.className=="related_subcontent_text reg_text_small"){
        var bracket = selectedLinkParent.getElementsByTagName("span")[1];//Find the "["
        selectedLinkParent.insertBefore(bracket, selectedLink);//Insert it before the first tag
        var comma = document.createElement("span"); comma.innerHTML=","; //create a COMMA 
        selectedLinkParent.insertBefore(comma, selectedLink.nextSibling); //Insert the COMMA between the first tag and the next one
    }*/
    
    selectedLink.className = returnAttr(selectedLink.className, " selected", "");//Deselect the previously selected tag link
    
    /*var clickedLinkParent = clickedLink.parentNode;// Sets the parentNode and will be used if its "related_subcontent_text reg_text_small"
    if (clickedLinkParent.className=="related_subcontent_text reg_text_small"){ 
       if (clickedLink.previousSibling.nodeType==3 || clickedLink.previousSibling.innerHTML==","){
           clickedLinkParent.RemoveChild(clickedLink.previousSibling);//Erases the previous COMMA
           if (clickedLink.previousSibling.nodeType==3 || clickedLink.previousSibling.innerHTML==","){
               clickedLinkParent.RemoveChild(clickedLink.previousSibling);//If the last RemoveChild erased a white space instead - erases the previous COMMA for real this time
           }
       }
       else if (clickedLink.nextSibling.nodeType==3 || clickedLink.nextSibling.innerHTML==","){
               clickedLinkParent.RemoveChild(clickedLink.nextSibling);//Erases a COMMA situated after the tag link
       }
       
       var bracket = clickedLinkParent.getElementsByTagName("span")[1]; //Create a "["
       clickedLinkParent.insertBefore(clickedLink, bracket); //Places it after the first tag link
    }*/
    
    clickedLink.className = clickedLink.className + " selected";//Turn the newly selected link into a selected one
}

var times=10,interval, objId="ErrSpan";
var msgElement;
function startBlinking()
{
	interval = window.setInterval(blinkErrMsg,100);
}

function blinkErrMsg()
{
	if (times>0)		
	{
		--times;
		if (msgElement!=null)
		{
		
			var curStatus=msgElement.style.visibility;			
			msgElement.style.visibility=((curStatus=="visible") ? "hidden" : "visible");	
		}
	}
	else
	{	
		times=10;
		window.clearInterval (interval);
		if (msgElement!=null)
			msgElement.style.visibility="visible";	
	}
}

var lastOpenQ;
var lastOpenA;
function handlePageFaq(divObj) {
	var questionDIV = divObj;
	
	if (document.all) {
		var answerDIV = divObj.nextSibling;
	} else {
		var answerDIV = divObj.nextSibling.nextSibling;
	}

	if (answerDIV.style.display == 'none') {
		if(!isNullOrUndefined(lastOpenQ))
			{//alert(111)
				lastOpenQ.className = 'page_faq_question';
				lastOpenA.style.display = 'none';
			}
		questionDIV.className = 'page_faq_question_open';
		answerDIV.style.display = '';
		lastOpenQ = questionDIV;
		lastOpenA = answerDIV;
	} else {
		questionDIV.className = 'page_faq_question';
		answerDIV.style.display = 'none';
	}
}

function secs2hms(secs) {
	m = Number(secs / 60).toFixed(); 
	s = secs % 60;
	h = Number(m / 60).toFixed(); 
	m = m % 60;
	return fillZero(String(h), 2) + ":" + fillZero(String(m), 2) + ":" + fillZero(String(s), 2);
}

function fillZero(num, rLength)
{
	var s = "";
	for (i=0; i<rLength-num.length; i++)
		s += "0"
	
	return s + num;
}

function loadDefault(obj) { 
    obj.src = appPathAnimatorIcons+"/default.jpg";
    //obj.src = "http://sharona/aniboom/upload/default.jpg";
}

//Gilad - for some reason appPathAnimationIcons is undefined
//please check this
function fixAnimationImg(obj) {
   obj.src = appPathAnimationIcons+"default.jpg";
   //obj.src = "http://sharona/aniboom/upload/default.jpg";
}
function refreshSession()
{
	window.setInterval(refreshSessionOnce, 80000);
}
function refreshSessionOnce()
{
	var url = appPathScript + "/Pages/InfraPages/KeepSessionAlive.aspx"
	AJAX.asyncWithCallback(url, "", "", true, false) ;
}
function  googlesyndication()
{
    document.getElementById('divTopBanners').style.display = "block";    
}

var arrBusIDs = new Array();
function ChooseCheckBox(id)
{   //debugger
    $('errMsg').style.display='none';
    var busSelected = $(id);
    var entityID = id.split('_');
    if(busSelected.className=='aCLASS')//$('chk_' + entityID[1]).checked == false)//busSelected.className=='aCLASS')
    {
        busSelected.className = 'selected';
        busSelected.style.backgroundColor = '#bebfc1';
        busSelected.onmouseover = function(){ moveOverRow(busSelected,'#bebfc1');}
        busSelected.onmouseout = function(){ moveOutRow(busSelected,'#bebfc1');}
        busSelected.firstChild.checked = true;
        //if($('chk_' + entityID[1]))
        $('chk_' + entityID[1] + "_" + entityID[2]).checked = true;
        arrBusIDs.push(entityID[1].toString());
    }
    else
    {
        busSelected.className = 'aCLASS';
        busSelected.style.backgroundColor = '#fff';
        busSelected.onmouseover = function(){ moveOverRow(busSelected);}
        busSelected.onmouseout = function(){ moveOutRow(busSelected);}
        busSelected.firstChild.checked = false;
        //if($('chk_' + entityID[1]))
        $('chk_' + entityID[1]).checked = false;
        for(i=0;i<arrBusIDs.length;i++)
        {
            if(arrBusIDs[i]==entityID[1])
            {
                arrBusIDs.splice(i,1);
                break;
            }
        }
    }
}




function getQueryStringParams() {
    var qsParm = new Array();
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i=0; i<parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0,pos);
            var val = parms[i].substring(pos+1);
            qsParm[key] = val;
        }
    }
    return qsParm;
}
function lackOfZero(num)
{
    if(num<10)
        num = '0' + num.toString();
    return num;
}

function ImageSwitch(id)
{
    var img = $(id);
    var temp = img.src;
    img.setAttribute('src',img.getAttribute('altsrc'));
    img.setAttribute('altsrc',temp);
}
//for using the 'asyncWithCallback' function and need the call back function just for event log and other stuff...
function GlobalCallBackFunc(response)
{
    var Msg = response.result;
}

function createNewElement(type, typeAttributes ,innerElement, containerID)
{
    var newElement = document.createElement(type);
    eval('newElement.' + typeAttributes);
    newElement.innerHTML = innerElement;
    document.getElementById(containerID).appendChild(newElement);
}
function moveOverRow(obj,setColor)
{
    obj.style.borderBottom = '1px dotted #E1E1E1';   
    if(setColor)
        obj.style.backgroundColor=setColor;
    else
        obj.style.backgroundColor='#fcfcfc';
    /*obj.style.cursor='pointer';*/
    /*obj.getElementsByTagName('a')[0].style.color='#fff'*/
}
function moveOutRow(obj,setColor)
{
    
    //obj.style.borderBottom = '1px dotted #E1E1E1';   
    if(setColor)
    {
        obj.style.backgroundColor=setColor;
    }
    else
        obj.style.backgroundColor='#fff';
    /*obj.style.cursor='normal';
    obj.getElementsByTagName('a')[0].style.color='#0000ee'*/
}
function showToolTip(idToDisplay)
{
    $(idToDisplay).style.visibility = 'visible';
}
function hideToolTip(idToDisplay)
{
    $(idToDisplay).style.visibility = 'hidden';
}
//DateTime
Date.prototype.toStringDDMMYYYY = function()
{
    var newDate = this.isLowerThan10(this.getDate()) + '/' + this.isLowerThan10(this.getMonth()+1) + '/' + this.isLowerThan10(this.getFullYear());
    return newDate.toString();
    //return this.toDateString();
}
Date.prototype.toStringMMDDYYYY = function()
{
//    this.setMinutes(this.getTimezoneOffset());
    var newDate = this.isLowerThan10(this.getMonth()+1) + '/' + this.isLowerThan10(this.getDate()) + '/' + this.isLowerThan10(this.getFullYear());
    return newDate.toString();
    //return this.toDateString();
}
Date.prototype.toStringMMDDYYYYminusUTC = function() {
    //debugger;
    this.setHours(this.getHours() + (this.getTimezoneOffset() / 60));
    var newDate = this.isLowerThan10(this.getMonth() + 1) + '/' + this.isLowerThan10(this.getDate()) + '/' + this.isLowerThan10(this.getFullYear());
    return newDate.toString();
    //return this.toDateString();
}
Date.prototype.toStringFullDate = function() {
    
    var arrDays = new Array(Resources.days_1, Resources.days_2, Resources.days_3, Resources.days_4, Resources.days_5, Resources.days_6, Resources.days_7);
    var arrMonths = new Array(Resources.months_1, Resources.months_2, Resources.months_3, Resources.months_4, Resources.months_5, Resources.months_6, Resources.months_7, Resources.months_8, Resources.months_9, Resources.months_10, Resources.months_11, Resources.months_12);
    var newDate;
    if (Resources.LangIso3Letters == 'eng')
        newDate = arrDays[this.getDay()] + ', ' + arrMonths[this.getMonth()] + ' ' + this.getDate() + ', ' + this.getFullYear();
    else
        newDate = Resources.day + ' ' + arrDays[this.getDay()] + ', ' + this.getDate() + ' ' + arrMonths[this.getMonth()] + ' ' + this.getFullYear();
    return newDate.toString();
    //return this.toDateString();
}
//returns this.getDate() + his summery name (e.g. 21'st)
Date.prototype.dayEnding = function()
{
    var dayEnding = this.getDate();
    var theDay = this.getDate();
    if(this.getDate() > 20)
    {
        theDay = parseInt(this.getDate(),10)%10;
    }
    switch(theDay)
    {
        case 1:
            dayEnding += '\'st';
        break;
        case 2:
            dayEnding += '\'nd';
        break;
        case 3:
            dayEnding += '\'rd';
        break;
        default:
        dayEnding += '\'th';
        break;
    }
    return dayEnding;
}
Date.prototype.toStringFullDateUTCminus = function(withStyle)
{
    this.setHours(this.getHours() + (this.getTimezoneOffset()/60));
    var arrDays = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    var arrMonths = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
    var newDate;
    if(withStyle)
        newDate = '<font color="#cc4b00">' + arrDays[this.getDay()]  + '</font>, ' +  arrMonths[this.getMonth()] + ' ' + this.getDate() + ' ' + this.getFullYear();
    else
        newDate = arrDays[this.getDay()]  + ', ' +  arrMonths[this.getMonth()] + ' ' + this.getDate() + ' ' + this.getFullYear();
    return newDate.toString();
    //return this.toDateString();
}
Date.prototype.toStringHHmm = function()
{
    return this.toTimeString().substring(0,5);
}
Date.prototype.toStringHHmmUTCminus = function()
{

    this.setHours(this.getHours() + (this.getTimezoneOffset()/60));
    return this.toTimeString().substring(0,5);
    
}
Date.prototype.isLowerThan10 = function(num)
{
    if(num<10)
        return '0' + num;
    else
        return num;
}
Date.prototype.add = function (sInterval, iNum){
  var dTemp = this;
  if (!sInterval || iNum == 0) return dTemp;
  switch (sInterval.toLowerCase()){
    case "ms":
      dTemp.setMilliseconds(dTemp.getMilliseconds() + iNum);
      break;
    case "s":
      dTemp.setSeconds(dTemp.getSeconds() + iNum);
      break;
    case "mi":
      dTemp.setMinutes(dTemp.getMinutes() + iNum);
      break;
    case "h":
      dTemp.setHours(dTemp.getHours() + iNum);
      break;
    case "d":
      dTemp.setDate(dTemp.getDate() + iNum);
      break;
    case "mo":
      dTemp.setMonth(dTemp.getMonth() + iNum);
      break;
    case "y":
      dTemp.setFullYear(dTemp.getFullYear() + iNum);
      break;
  }
  return dTemp;
}
//String
String.prototype.allTrim = function () {
    return this.replace(/\s/g, "");
};
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
function createFlowingDiv(msg,className)
{
    var obj = document.createElement('div');
    obj.className = className;
    obj.innerHTML = msg;
}

var staticMessageBox = {
    show: function(msg, msgType, Obj, toReplace) {
        removeMsg();
        var containerObj = document.createElement('div');
        containerObj.setAttribute('id', 'topMsg')
        containerObj.className = 'containerMsg';
        //                            var aObj = document.createElement('a');
        //                            aObj.href = 'javascript://';
        //                            aObj.onclick = removeMsg;
        //                            aObj.innerHTML = 'hide'
        var ulObj = document.createElement('ul');
        if (msgType == 'error') {
            ulObj.className = 'errMsg';
        }
        else if (msgType == 'success') {
            ulObj.className = 'succMsg';
        }
        else if (msgType == 'note') {
            ulObj.className = 'noteMsg';
        }
        else if (msgType == 'empty') {
            ulObj.className = 'emptyMsg';
        }
        var liObj;
        var arrMsg = msg.split(';');
        for (i = 0; i < arrMsg.length; i++) {
            liObj = document.createElement('li');
            liObj.innerHTML = arrMsg[i];
            ulObj.appendChild(liObj);
        }
        containerObj.appendChild(ulObj);
        //                            containerObj.appendChild(aObj);

        if (!isNullOrUndefined(toReplace) && toReplace.toString() == 'true') {
            var ddd = document.createElement('div');
            ddd.appendChild(containerObj);
            Obj.innerHTML = ddd.innerHTML;
        }
        else {
            var topMsgOldContainer = $('topMsg'); 
            if (!topMsgOldContainer && !isNullOrUndefined(Obj.childNodes)) {

                if (Obj.childNodes.length > 0)
                    Obj.insertBefore(containerObj, Obj.childNodes.item(0));
                else
                    Obj.appendChild(containerObj);
            }
            else if ($('topMsg')) {
                
                $('topMsg').innerHTML = '';
                topMsgOldContainer.innerHTML = containerObj.innerHTML;
            }
        }

    }

};

var blockMgr = {
    addBlock: function(lastBlock, data, target, collapseBlockID, fadeTargetID, showFade, showAnim) {
        //debugger;
        if (!lastBlock)
            this.lastBlock = 0;
        else
            this.lastBlock = lastBlock;

        if (data)
            this.data = data;
        else
            this.data = [];

        if (target)
            this.target = target;
        else
            this.target = $('target1');

        this.template = document.createElement('div');

        if (fadeTargetID)
            this.fadeTargetID = fadeTargetID;
        else
            this.fadeTargetID = null;

        this.template.setAttribute('id', 'dynTarget_New' + this.lastBlock.toString());
        this.target.insertBefore(this.template, this.target.childNodes.item(0));
        setRepeater(this.data, this.template);

        if (collapseBlockID)
            this.collapseBlockID = $(collapseBlockID);
        else
            this.collapseBlockID = null;

        if (showFade)
            Fat.fade_element(this.fadeTargetID);
        if (this.collapseBlockID) {
            if (showAnim) {
                this.collapseBlockID.style.display = '';
                Fat.fade_element(this.collapseBlockID.id);//this.fadeTargetID);
                //setTimeout("animatedMethodSelect('" + this.collapseBlockID.id + "')", 500);
                //animatedMethodSelect(this.collapseBlockID.id);
            }
        }
    }
};
function dayOfWeekFromInt(dayNum)
{
    switch(dayNum)
    {
        case 0:
            return 0;
            break;
        case 1:
            return 'Sunday';
            break;
        case 2:
            return 'Monday';
            break;
        case 3:
            return 'Tuesday';
            break;
        case 4:
            return 'Wednesday';
            break;
        case 5:
            return 'Thursday';
            break;
        case 6:
            return 'Friday';
            break;
        case 7:
            return 'Saturday';
            break;
        default:
        break;
    }
}

function dayOfWeekShortFromInt(dayNum)
{
    switch(dayNum)
    {
        case 0:
            return 0;
            break;
        case 1:
            return Resources.days_1;
            break;
        case 2:
            return Resources.days_2;
            break;
        case 3:
            return Resources.days_3;
            break;
        case 4:
            return Resources.days_4;
            break;
        case 5:
            return Resources.days_5;
            break;
        case 6:
            return Resources.days_6;
            break;
        case 7:
            return Resources.days_7;
            break;
        default:
        break;
    }
}
function getMouseCoords(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event; 
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
	var mousecoords = new Array();
	mousecoords.push(posx);
	mousecoords.push(posy);
	return mousecoords;
}
//function key13Down(x)
//{
//	var keyCode;
//	if(document.all)
//		keyCode = event.keyCode;
//	else
//		keyCode = x.keyCode;	
//	
//	if(keyCode == 13)
//	{			
//		var aObjs = document.getElementsByTagName("A");
//		var txt = document.getElementById('tdTxt').getElementsByTagName('input')[0];	  
//		if(txt.value==trimString("") || txt.value==trimString("Type search"))
//			return;
//	
//		for (var i=0; i<aObjs.length; i++)
//		{
//			if(aObjs[i].id.indexOf("lbSerach") != -1)
//			{
//				GoSearch('');
//			}
//		}	
//		return false;
//	}	
//}
function loadLoaderIMG(stylingImg,stylingDiv)
{
    if (!styling) var styling = 'none'; 
    var loaderImg = '<div' + stylingDiv + '><img ' + stylingImg + ' src="http://' + Resources.SiteDomain + '/' + Resources.ImagesDirectory + '/loader/ajax-loader.gif" style="width:16px; height:16px;" /></div>'
    return loaderImg;
}
function loadLoaderTxt(stylingImg,stylingDiv)
{
    if(!styling) var styling = 'style="color:red;font-size:11px;text-align:left"';
    var loaderTxt = '<span '+styling+'>Loading...</span>';
    return loaderTxt;
}
function stillInBetaMsg(styling)
{
    if(!styling) var styling = 'defaultFeedbackMsg';
    var betaMsg = '<div class="' + styling + '">' + Resources.alert_BetaErrorMsg + '</div>'
    return betaMsg;
}
function getDayBlockTemplate(item)
{
    /*days blocks design*/
    var blockTemplate = item.template;
    var blockHeader = item.allTemplates.dayrow;//the day block header
    var blockMiddle = item.allTemplates.item;//the time content example: '11:00 - 12:00'
    var blockFooter = item.allTemplates.dayrowfooter;//the day block footer
    var itemIndex = item.itemIndex;//the binding item index
    var currentItem_DayOfTheWeek = item.dataItem.DayOfWeek;
    
    if(itemIndex>0)
        var previousItem_DayOfTheWeek = item.parentDataSrc.SerivcetimesList[itemIndex-1].DayOfWeek;
    var hasNextItem = false;//debugger
    if(item.parentDataSrc.SerivcetimesList[itemIndex+1])
        hasNextItem = true;

    if(itemIndex==0)//first item?
    {
        blockTemplate = blockHeader + blockMiddle;
        if(!hasNextItem)//if it's the last item
            blockTemplate += blockFooter;//close block
    }
    else
    {//if NOT the first item
        if(currentItem_DayOfTheWeek == previousItem_DayOfTheWeek)//and the same day of the week as previous item
        {
            blockTemplate = blockMiddle;
            if(!hasNextItem)//if it's the last item
                blockTemplate += blockFooter;//close block
        }
        else
        {//if NOT the same day as the previous item
            blockTemplate = blockFooter + blockHeader + blockMiddle;//close the previous block and open a new block with the first item inside
            if(!hasNextItem)//if it's the last item
                blockTemplate += blockFooter;//close block
        }
    }
    /*END days blocks design*/
    
    return blockTemplate;
}
function removeBlockFromDOM(removedObjId)
{
    
    var card = $(removedObjId);
    if(!card)return;
    card.parentNode.removeChild(card);
}
function removeMsg()
{
    if($('topMsg'))
    $('topMsg').parentNode.removeChild($('topMsg'))
}
function renderAppointmentsToCancel(data,template,target)
{//debugger
    appointMgrForDel = new MyAppointmentsMgr(); 
    //obtaining the template
    var strTemplate = template;//
    //obtaining the target element 
    var oTargetRow= target;
    var oTargetButtons = '';//$('template2').value;
    var oMapping = {
                        APP_ID          : "AppointmentID"
                        ,CLIENT_NAME    : function(item){return (item.CustomerFirstName == '' && item.CustomerLastName == ''?item.Comment:item.CustomerFirstName + " " + item.CustomerLastName);}
                        ,DATE_TIME      : function(item){return item.StartTime.toStringMMDDYYYY() + " " + item.StartTime.toStringHHmm();}
                        ,SERVICE_NAME   : "ServiceName"
                        ,SERVICE_ID     : "ServiceID"
                        
                    };
    appointMgrForDel.init(strTemplate,oTargetButtons,data,oTargetRow,1,$('tdPageNums'),data.length,oMapping);
    var htmlString = appointMgrForDel.execute();
    return htmlString;
}
function getNextSibling(startBrother){
  endBrother=startBrother.nextSibling;
  if(endBrother)
  {
      while(endBrother.nodeType!=1){
          if(endBrother.nextSibling)
          {
            endBrother = endBrother.nextSibling;
          }
          else
          {
            endBrother = null;
            break;
          }
      }
  }
  return endBrother;
}
//Returns the filter (categoryID, cityID...) ID from the arrayID
function getAutoCompID(obj,arrayID)
{
    if(!isNullOrUndefined(obj.wordID))
        return arrayID[obj.wordID];
    else
        return -1;

}
function EmailCheck(src) {
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);
     return regex.test(src);
    }
Date.prototype.compareDate = function(compareTo)
{
    var date1 = new Date();
    date1.setDate(this.getDate());
    date1.setMonth(this.getMonth());
    date1.setFullYear(this.getFullYear());
    var date2 = new Date();
    date2 = compareTo;
    date1.setMinutes(0);
    date1.setHours(0);
    date1.setSeconds(0);
    date1.setMilliseconds(0);
    date2.setMinutes(0);
    date2.setHours(0);
    date2.setSeconds(0);
    date2.setMilliseconds(0);
    return date1 - date2;
}
function getSelectedDate()
{
    var arrDates = call.getSelectedDates()[0];
    if(arrDates)
    {
        return arrDates;
        
    }
    else
    {
        return new Date();
    }
}
function insertText(id,defaultTxt)
{
    
    
    var txtObj = $(id);
    
    if(!txtObj)return;
    //if(txtObj.value != '')return;
    
    if(txtObj.value == '')
    {
        txtObj.style.color = '#999';
        txtObj.value = defaultTxt;
    }
}
function removeText(id,defaultTxt)
{
    
    
    var txtObj = $(id);
    if(!txtObj)return;
    //if(txtObj.value == '')return;
    if(txtObj.value == defaultTxt)
    {
        txtObj.value = '';
        txtObj.style.color = '#000';
    }
        
}
function checkFields(id,includeEmpty)
{
    //alert('check point');
    var inpts = $(id).getElementsByTagName('input');
    hideErr(inpts);
    var params = new Array();
    var err = new Array();
    var autoCompObj;
    for(i=0;i<inpts.length;i++)
    {
        
            if(inpts[i].type == 'text' || inpts[i].type == 'password')
            {
            
                if(inpts[i].value.allTrim() != '')
                {
                    
                    if(inpts[i].id.indexOf('email')>-1)
                    {
                        if(!EmailCheck(inpts[i].value))
                            err.push(inpts[i].id)
                        else
                            params.push("'" +inpts[i].value+ "'");
                    }
                    else if(inpts[i].id=='fullName')
                    {
                        params.push("'" + inpts[i].value.split(' ')[0] + "'");
                        params.push("'" + inpts[i].value.split(' ')[1] + "'");
                    }
                    else if(inpts[i].id=='zipCode')
                    {
                        params.push(parseInt(inpts[i].value,10));
                    }
                    else if(inpts[i].id=='city' || inpts[i].id=='state' || inpts[i].id=='country' || inpts[i].id=='category')
                    {//debugger
                        autoCompObj = eval($(inpts[i].id).getAttribute('autoCompObj'));
                        if(autoCompObj.wordID!=null)
                            params.push(autoCompObj.actb_idsArray[autoCompObj.wordID]);
                        else
                            params.push(-1);
                    }
                    else
                    {   
                        if(inpts[i].id == 'password' && inpts[i].getAttribute('needVerify')==='true')
                        {
                            if(!checkLength())
                                err.push(inpts[i].id);
                            else
                                params.push("'" +inpts[i].value+ "'");
                        }
                        else if(inpts[i].id == 'verifyPassword')
                        {
                            if($('err_verifyPassword').style.visibility == 'visible')
                                err.push(inpts[i].id)
                           
                        }
                        else
                            params.push("'" +inpts[i].value+ "'");
                    }
                    
                }
                else if(inpts[i].id=='city' || inpts[i].id=='state' || inpts[i].id=='country' || inpts[i].id=='category')
                {
                        if(inpts[i].getAttribute('isREQUIRED')==='true')
                            err.push(inpts[i].id)
                        else
                            params.push(-1);
                }
                else if(includeEmpty && inpts[i].getAttribute('isREQUIRED')!='true')
                {
                    if(inpts[i].id.toLowerCase() == 'zipcode')
                        params.push(-1);
                    else
                        params.push("'" +inpts[i].value+ "'");
                }
                else
                {
                    err.push(inpts[i].id)
                }
            }
        
    }
    if(err.length > 0)
    {//debugger
        for(i=0;i<err.length;i++)
            $('err_' + err[i]).style.visibility = 'visible';
        return null;
    }
    else
    {
        return params;
        
    }
}
function hideErr(err)
{
    if(err.length > 0)
    {
        for(i=0;i<err.length;i++)
        {
            if($('err_' + err[i].id))
                $('err_' + err[i].id).style.visibility = 'hidden';
        }
    }
}
function nullToEmptyString(txt)
{
    if(txt == null || txt == 'null' || txt == -1 || txt == '-1')
    {
        return txt = '';
    }
    else
    {
        return txt;
    }
    
}
function getDropDownValues(id,params)
{
    if(isNullOrUndefined(params))return;
    var selects = $(id).getElementsByTagName('select');
    
    for(i=0;i<selects.length;i++)
    {
        params.push(-1);
    }
    return params;
}
function showLoader(id)
{
    $(id).className = "hide";
    $('loader').innerHTML = loadLoaderIMG();
}
function logout()
{
    removeMsg();
    jsonObj.asyncWithCallback('jsonHandler','Logout',null,'callbackLogout');
}   
function getTime(id,lang)
{
    var obj;
    if(lang=='en')
        obj = $('td_0_' + id);
    else if(lang=='he')
        obj = $('td_0_' + id);
        
    return obj.innerHTML;
}
//String.prototype.replaceQuotes = function(chatToReplace){
//    if(!chatToReplace)chatToReplace="^";
//    var noquotes = /\"/g;
//     return this.replace(noquotes, chatToReplace);
//}
String.prototype.replaceQuotes = function(chatToReplace){
    if(!chatToReplace)chatToReplace="~";
    var noquotes = /\'|"/g;
     return this.replace(noquotes, chatToReplace);
}
//String.prototype.replaceBackQuotes = function(charToReplace){
//    if(!charToReplace)charToReplace="X";
//    var noquotes = /^/g;
//     return this.replace(noquotes, charToReplace);
//}
String.prototype.replaceBackQuotes = function(charToReplace){
    if(!charToReplace)charToReplace="'";
    var noquotes = /~/g;
    return this.replace(noquotes, charToReplace);
}
//String.prototype.replaceBackQuotesAndApostrophe = function(chatToReplaceQuotes,chatToReplaceApostrophe){
//    var noquotes = this.replaceBackQuotes(chatToReplaceQuotes);
//    return noquotes.replaceBackApostrophe(chatToReplaceApostrophe);
//    
//    
//}
//String.prototype.replaceQuotesAndApostrophe = function(chatToReplaceQuotes,chatToReplaceApostrophe){
//    var noquotes = this.replaceQuotes(chatToReplaceQuotes)
//    return noquotes.replaceApostrophe(chatToReplaceApostrophe);
//    
//    
//}

/*
E.g. "Piper's Wood" or 'Piper's Wood' in quotes
to be changed to Piper's Wood
and not Pipers Wood
(http://codingforums.com/archive/index.php?t-15848.html)
return str.replace( /['"](?!\b)/g , "").replace( /([^\w])['"]/g, "$1" ).replace( /^['"]|['"]$/g, "" );
*/
/// Swap Images   ////////////////////////////////////////////
//////////////////////////////////////////////////////////////
function swapImgSrc(id)
{
 with (document.getElementById(id))
 {
	//alert(attributes["altsrc"].value);
  attributes["altsrc"].value;
  var saveSrc = src;
  src = attributes["altsrc"].value;
  attributes["altsrc"].value = saveSrc;
 }
}
function appointmentType(id) {
    switch (id) {
        case 'all':
            return '';
            break;
        case 'approved':
            return Resources.myBusApp_approved;
            break;
        case 'pending':
            return Resources.myBusApp_pending;
            break;
        case 'cancelled':
            return Resources.myBusApp_cancelled;
            break;
        case 'blocked':
            return Resources.myBusApp_blocked;
            break;
        case 'available':
            return Resources.myBusApp_available;
            break;
    }
}
function ShowHideElement(element) {
    if (!element) return;
    if (element.style.display == 'none')
        element.style.display = '';
    else
        element.style.display = 'none';
}
function openEdit(id, id2, updateInputs) {
    var entityID = id.split('_')[1];
    if (updateInputs == 1)
        fillInputs(entityID);
    else if (updateInputs == 2)
        fillLabals(entityID);
    var obj = $(id);
    var obj2 = $(id2);
    if (obj.style.display == '') {
        obj.style.display = 'none';
        obj2.style.display = '';
    }
    else {
        obj.style.display = '';
        obj2.style.display = 'none';
    }
}
function fillInputs(entityID) {
    fillText($('txtFullName_' + entityID), $('lblFullName_' + entityID).innerHTML.trim());
    fillText($('txtAddress_' + entityID), $('lblAddress_' + entityID).innerHTML.trim());
    fillText($('txtPhone_' + entityID), $('lblPhone_' + entityID).innerHTML.trim());
    fillText($('txtMobile_' + entityID), $('lblMobile_' + entityID).innerHTML.trim());
    fillText($('txtPrice_' + entityID), $('lblPrice_' + entityID).innerHTML.trim());
}
function fillLabals(entityID) {
    $('lblFullName_' + entityID).innerHTML = $('txtFullName_' + entityID).value;
    $('lblAddress_' + entityID).innerHTML = $('txtAddress_' + entityID).value;
    $('lblPhone_' + entityID).innerHTML = $('txtPhone_' + entityID).value;
    $('lblMobile_' + entityID).innerHTML = $('txtMobile_' + entityID).value;
    $('lblPrice_' + entityID).innerHTML = $('txtPrice_' + entityID).value;

}

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else
        countfield.value = maxlimit - field.value.length;
}
/*
Date Validation
*/
// 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 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
}

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
}

function ValidateForm(obj){
    //var dt=document.frmSample.txtDate
    var dt = obj;
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
 /*
 end Date Validation
 */