//General
//for example: instead of each module writing out script found in moduleMaxMin_OnClick have the functionality cached
//

var DNN_COL_DELIMITER = String.fromCharCode(16);
var DNN_ROW_DELIMITER = String.fromCharCode(15);
var __dnn_m_bPageLoaded = false;

window.onload = __dnn_Page_OnLoad;

function __dnn_ClientAPIEnabled()
{
	return typeof(dnn) != 'undefined';
}


function __dnn_Page_OnLoad()
{
	if (__dnn_ClientAPIEnabled())
	{
		var sLoadHandlers = dnn.getVar('__dnn_pageload');
		if (sLoadHandlers != null)
			eval(sLoadHandlers);
		
		dnn.dom.attachEvent(window, 'onscroll', __dnn_bodyscroll);
	}
	__dnn_m_bPageLoaded = true;
}


function __dnn_KeyDown(iKeyCode, sFunc, e)
{
	if (e == null)
		e = window.event;

	if (e.keyCode == iKeyCode)
	{
		eval(unescape(sFunc));
		return false;
	}
}

function __dnn_bodyscroll() 
{
	var oF=document.forms[0];	
	if (__dnn_ClientAPIEnabled() && __dnn_m_bPageLoaded)
		oF.ScrollTop.value=document.documentElement.scrollTop ? document.documentElement.scrollTop : dnn.dom.getByTagName("body")[0].scrollTop;
}

function __dnn_setScrollTop(iTop)
{
	if (__dnn_ClientAPIEnabled())
	{
		if (iTop == null)
			iTop = document.forms[0].ScrollTop.value;
	
		var sID = dnn.getVar('ScrollToControl');
		if (sID != null && sID.length > 0)
		{
			var oCtl = dnn.dom.getById(sID);
			if (oCtl != null)
			{
				iTop = dnn.dom.positioning.elementTop(oCtl);
				dnn.setVar('ScrollToControl', '');
			}
		}
		window.scrollTo(0, iTop);
	}
}

//Focus logic
function __dnn_SetInitialFocus(sID)
{
	var oCtl = dnn.dom.getById(sID);	
	if (oCtl != null && __dnn_CanReceiveFocus(oCtl))
		oCtl.focus();
}	

function __dnn_CanReceiveFocus(e)
{
	//probably should call getComputedStyle for classes that cause item to be hidden
	if (e.style.display != 'none' && e.tabIndex > -1 && e.disabled == false && e.style.visible != 'hidden')
	{
		var eParent = e.parentElement;
		while (eParent != null && eParent.tagName != 'BODY')
		{
			if (eParent.style.display == 'none' || eParent.disabled || eParent.style.visible == 'hidden')
				return false;
			eParent = eParent.parentElement;
		}
		return true;
	}
	else
		return false;
}

//Max/Min Script
function __dnn_ContainerMaxMin_OnClick(oLnk, sContentID)
{
	var oContent = dnn.dom.getById(sContentID);
	if (oContent != null)
	{
		var oBtn = oLnk.childNodes[0];
		var sContainerID = oLnk.getAttribute('containerid');
		var sCookieID = oLnk.getAttribute('cookieid');
		var sCurrentFile = oBtn.src.toLowerCase().substr(oBtn.src.lastIndexOf('/'));
		var sMaxFile;
		var sMaxIcon;
		var sMinIcon;

		if (dnn.getVar('min_icon_' + sContainerID))
			sMinIcon = dnn.getVar('min_icon_' + sContainerID);
		else
			sMinIcon = dnn.getVar('min_icon');

		if (dnn.getVar('max_icon_' + sContainerID))
			sMaxIcon = dnn.getVar('max_icon_' + sContainerID);
		else
			sMaxIcon = dnn.getVar('max_icon');

		sMaxFile = sMaxIcon.toLowerCase().substr(sMaxIcon.lastIndexOf('/'));

		var iNum = 5;
		if (oLnk.getAttribute('animf') != null)
			iNum = new Number(oLnk.getAttribute('animf'));
			
		if (sCurrentFile == sMaxFile)
		{
			oBtn.src = sMinIcon;				
			//oContent.style.display = '';
			dnn.dom.expandElement(oContent, iNum);
			oBtn.title = dnn.getVar('min_text');
			if (sCookieID != null)
			{
				if (dnn.getVar('__dnn_' + sContainerID + ':defminimized') == 'true')
					dnn.dom.setCookie(sCookieID, 'true', 365);
				else
					dnn.dom.deleteCookie(sCookieID);
			}
			else
				dnn.setVar('__dnn_' + sContainerID + '_Visible', 'true');
		}
		else
		{
			oBtn.src = sMaxIcon;				
			//oContent.style.display = 'none';
			dnn.dom.collapseElement(oContent, iNum);
			oBtn.title = dnn.getVar('max_text');
			if (sCookieID != null)
			{
				if (dnn.getVar('__dnn_' + sContainerID + ':defminimized') == 'true')
					dnn.dom.deleteCookie(sCookieID);
				else
					dnn.dom.setCookie(sCookieID, 'false', 365);				
			}
			else
				dnn.setVar('__dnn_' + sContainerID + '_Visible', 'false');			
		}
		
		return true;	//cancel postback
	}
	return false;	//failed so do postback
}

function __dnn_Help_OnClick(sHelpID)
{
	var oHelp = dnn.dom.getById(sHelpID);
	if (oHelp != null)
	{
		if (oHelp.style.display == 'none')
			oHelp.style.display = '';
		else
			oHelp.style.display = 'none';

		return true;	//cancel postback
	}
	return false;	//failed so do postback
}

function __dnn_SectionMaxMin(oBtn, sContentID)
{
	var oContent = dnn.dom.getById(sContentID);
	if (oContent != null)
	{
		var sMaxIcon = oBtn.getAttribute('max_icon');
		var sMinIcon = oBtn.getAttribute('min_icon');
		var bCallback = oBtn.getAttribute('userctr') != null;
		var sVal;
		if (oContent.style.display == 'none')
		{
			oBtn.src = sMinIcon;				
			oContent.style.display = '';
			if (bCallback)
			    sVal = 'True';
			else
			    dnn.setVar(oBtn.id + ':exp', 1);
		}
		else
		{
			oBtn.src = sMaxIcon;				
			oContent.style.display = 'none';
			if (bCallback)
			    sVal = 'False';
			else
                dnn.setVar(oBtn.id + ':exp', 0);
		}
		if (bCallback)
		    dnncore.setUserProp(oBtn.getAttribute('userctr'), oBtn.getAttribute('userkey'), sVal, null);
		return true;	//cancel postback
	}
	return false;	//failed so do postback
}

//Drag N Drop
function __dnn_enableDragDrop()
{
	var aryConts = dnn.getVar('__dnn_dragDrop').split(";");	
	var aryTitles;

	for (var i=0; i < aryConts.length; i++)
	{
		aryTitles = aryConts[i].split(" ");
		if (aryTitles[0].length > 0)
		{			
			var oCtr = dnn.dom.getById(aryTitles[0]);
			var oTitle = dnn.dom.getById(aryTitles[1]);
			if (oCtr != null && oTitle != null)
			{
				oCtr.setAttribute('moduleid', aryTitles[2]);
				dnn.dom.positioning.enableDragAndDrop(oCtr, oTitle, '__dnn_dragComplete()', '__dnn_dragOver()');
			}	
		}
	}
}

var __dnn_oPrevSelPane;
var __dnn_oPrevSelModule;
var __dnn_dragEventCount=0;
function __dnn_dragOver()
{
	__dnn_dragEventCount++;
	if (__dnn_dragEventCount % 75 != 0)	//only calculate position every 75 events
		return;
	
	var oCont = dnn.dom.getById(dnn.dom.positioning.dragCtr.contID);

	var oPane = __dnn_getMostSelectedPane(dnn.dom.positioning.dragCtr);
		
	if (__dnn_oPrevSelPane != null)	//reset previous pane's border
		__dnn_oPrevSelPane.pane.style.border = __dnn_oPrevSelPane.origBorder;

	if (oPane != null)
	{		
		__dnn_oPrevSelPane = oPane;
		oPane.pane.style.border = '4px double ' + DNN_HIGHLIGHT_COLOR;
		var iIndex = __dnn_getPaneControlIndex(oCont, oPane);

		var oPrevCtl;
		var oNextCtl;
		for (var i=0; i<oPane.controls.length; i++)
		{
			if (iIndex > i && oPane.controls[i].id != oCont.id)
				oPrevCtl = oPane.controls[i];
			if (iIndex <= i && oPane.controls[i].id != oCont.id)
			{
				oNextCtl = oPane.controls[i];
				break;
			}
		}			
		
		if (__dnn_oPrevSelModule != null)
			dnn.dom.getNonTextNode(__dnn_oPrevSelModule.control).style.border = __dnn_oPrevSelModule.origBorder;
			

		if (oNextCtl != null)
		{
			__dnn_oPrevSelModule = oNextCtl;
			dnn.dom.getNonTextNode(oNextCtl.control).style.borderTop = '5px groove ' + DNN_HIGHLIGHT_COLOR;
		}
		else if (oPrevCtl != null)
		{
			__dnn_oPrevSelModule = oPrevCtl;
			dnn.dom.getNonTextNode(oPrevCtl.control).style.borderBottom = '5px groove ' + DNN_HIGHLIGHT_COLOR;
		}
	}
}

function __dnn_dragComplete()
{
	var oCtl = dnn.dom.getById(dnn.dom.positioning.dragCtr.contID);
	var sModuleID = oCtl.getAttribute('moduleid');
	
	if (__dnn_oPrevSelPane != null)
		__dnn_oPrevSelPane.pane.style.border = __dnn_oPrevSelPane.origBorder;

	if (__dnn_oPrevSelModule != null)
		dnn.dom.getNonTextNode(__dnn_oPrevSelModule.control).style.border = __dnn_oPrevSelModule.origBorder;
		
	var oPane = __dnn_getMostSelectedPane(dnn.dom.positioning.dragCtr);
	var iIndex;
	if (oPane == null)
	{
		var oPanes = __dnn_Panes();
		for (var i=0; i<oPanes.length; i++)
		{
			if (oPanes[i].id == oCtl.parentNode.id)
				oPane = oPanes[i];
		}
	}	
	if (oPane != null)
	{
		iIndex = __dnn_getPaneControlIndex(oCtl, oPane);
		__dnn_MoveToPane(oPane, oCtl, iIndex);

		dnn.callPostBack('MoveToPane', 'moduleid=' + sModuleID, 'pane=' + oPane.paneName, 'order=' + iIndex * 2); 
	}
}

function __dnn_MoveToPane(oPane, oCtl, iIndex)
{

	if (oPane != null)
	{
		var aryCtls = new Array();
		for (var i=iIndex; i<oPane.controls.length; i++)
		{
			if (oPane.controls[i].control.id != oCtl.id)
				aryCtls[aryCtls.length] = oPane.controls[i].control;

			dnn.dom.removeChild(oPane.controls[i].control);
		}
		dnn.dom.appendChild(oPane.pane, oCtl);
		oCtl.style.top=0;
		oCtl.style.left=0;
		oCtl.style.position = 'relative';
		for (var i=0; i<aryCtls.length; i++)
		{
			dnn.dom.appendChild(oPane.pane, aryCtls[i]);
		}
		__dnn_RefreshPanes();
	}
	else
	{
		oCtl.style.top=0;
		oCtl.style.left=0;
		oCtl.style.position = 'relative';
	}
}

function __dnn_RefreshPanes()
{
	var aryPanes = dnn.getVar('__dnn_Panes').split(';');
	var aryPaneNames = dnn.getVar('__dnn_PaneNames').split(';');
	__dnn_m_aryPanes = new Array();
	for (var i=0; i<aryPanes.length; i++)
	{
		if (aryPanes[i].length > 0)
			__dnn_m_aryPanes[__dnn_m_aryPanes.length] = new __dnn_Pane(dnn.dom.getById(aryPanes[i]), aryPaneNames[i]);
	}
}

var __dnn_m_aryPanes;
var __dnn_m_aryModules;
function __dnn_Panes()
{
	if (__dnn_m_aryPanes == null)
	{
		__dnn_m_aryPanes = new Array();
		__dnn_RefreshPanes();
	}
	return __dnn_m_aryPanes;
}

function __dnn_Modules(sModuleID)
{
	if (__dnn_m_aryModules == null)
		__dnn_RefreshPanes();
	
	return __dnn_m_aryModules[sModuleID];
}

function __dnn_getMostSelectedPane(oContent)
{
	var oCDims = new dnn.dom.positioning.dims(oContent);
	var iTopScore=0;
	var iScore;
	var oTopPane;
	for (var i=0; i<__dnn_Panes().length; i++)
	{
		var oPane = __dnn_Panes()[i];
		var oPDims = new dnn.dom.positioning.dims(oPane.pane);
		iScore = dnn.dom.positioning.elementOverlapScore(oPDims, oCDims);
		
		if (iScore > iTopScore)
		{
			iTopScore = iScore;
			oTopPane = oPane;
		}
	}
	return oTopPane;
}

function __dnn_getPaneControlIndex(oContent, oPane)
{
	if (oPane == null)
		return;
	var oCDims = new dnn.dom.positioning.dims(oContent);
	var oCtl;
	
	if (oPane.controls.length == 0)
		return 0;
	for (var i=0; i<oPane.controls.length; i++)
	{
		oCtl = oPane.controls[i];
		var oIDims = new dnn.dom.positioning.dims(oCtl.control);
		if (oCDims.t < oIDims.t)
			return oCtl.index;
	}
	if (oCtl != null)
		return oCtl.index+1;
	else
		return 0;
}

//Objects
function __dnn_Pane(ctl, sPaneName)
{
	this.pane = ctl;
	this.id = ctl.id;
	this.controls = new Array();
	this.origBorder = ctl.style.border;
	this.paneName = sPaneName;
	
	var iIndex = 0;
	var strModuleOrder='';
	
	for (var i=0; i<ctl.childNodes.length; i++)
	{
		var oNode = ctl.childNodes[i];
		if (dnn.dom.isNonTextNode(oNode))	
		{
			if (__dnn_m_aryModules == null)
				__dnn_m_aryModules = new Array();

			//if (oNode.tagName == 'A' && oNode.childNodes.length > 0)
			//	oNode = oNode.childNodes[0];	//DNN now embeds anchor tag 
				
			var sModuleID = oNode.getAttribute('moduleid');
			
			
			
			if (sModuleID != null && sModuleID.length > 0)
			{
				strModuleOrder += sModuleID + '~';
				this.controls[this.controls.length] = new __dnn_PaneControl(oNode, iIndex);
				__dnn_m_aryModules[sModuleID] = oNode.id;
				iIndex+=1;
			}
		}
	}
	this.moduleOrder = strModuleOrder;

}

function __dnn_PaneControl(ctl, iIndex)
{
	this.control = ctl;
	this.id = ctl.id;
	this.index = iIndex;
	this.origBorder = ctl.style.border;
	
}

//move towards dnncore ns.  right now only for personalization
function __dnncore()
{
    this.GetUserVal = 0;
    this.SetUserVal = 1;
}

__dnncore.prototype = {
getUserProp: function(sNameCtr, sKey, pFunc) {
    this._doUserCallBack(dnncore.GetUserVal, sNameCtr, sKey, null, new dnncore.UserPropArgs(sNameCtr, sKey, pFunc));
},

setUserProp: function(sNameCtr, sKey, sVal, pFunc) {
    this._doUserCallBack(dnncore.SetUserVal, sNameCtr, sKey, sVal, new dnncore.UserPropArgs(sNameCtr, sKey, pFunc));
},

_doUserCallBack: function(iType, sNameCtr, sKey, sVal, pFunc) {
    if (dnn && dnn.xmlhttp)
    {
        var sPack = iType + COL_DELIMITER + sNameCtr + COL_DELIMITER + sKey + COL_DELIMITER + sVal;
        dnn.xmlhttp.doCallBack('__Page',sPack,dnncore._callBackSuccess,pFunc,dnncore._callBackFail,null,true,null,0);
    }
    else
        alert('Client Personalization not enabled');
},

_callBackSuccess: function (result, ctx, req) {
    if (ctx.pFunc)
        ctx.pFunc(ctx.namingCtr, ctx.key, result);
},

_callBackFail: function (result, ctx) {
	window.status = result;
}
}

__dnncore.prototype.UserPropArgs = function(sNameCtr, sKey, pFunc)
{
    this.namingCtr = sNameCtr;
	this.key = sKey;
	this.pFunc = pFunc;
}

var dnncore = new __dnncore();


//by Simon
String.prototype.startsWith=function(s){
      return s!=null && s.length<=this.length  && this.substring(0,s.length)==s;
	 };
String.prototype.trim=function() { return this.replace(/(\s*$)|(^\s*)/g, '');};

function $(id){return document.getElementById(id);};

function $wait(id){$(id).style.cursor='wait';};

function $disabled(id){$(id).disabled=true;};

function $enabled(id){$(id).disabled=false;};

function $h(o){o.style.display='none'};

function $s(o){o.style.display='block';};

function _h(o){o.style.visibility='hidden';};
function _s(o){o.style.visibility='visible';};

function $H(id){var o=$(id);if(o!=null)$h(o);};

function $S(id){var o=$(id);if(o!=null)$s(o);};

function $F(id){var o=$(id);if(o==null) return null; return o.value.trim();};

function $C(id){var o=$(id);if(o!=null)o.value='';};

// by simon

function getposOffset(what){var parentEl=what.offsetParent;var x_offset=what.offsetLeft;var y_offset=what.offsetTop;while (parentEl!=null){x_offset+=parentEl.offsetLeft;y_offset+=parentEl.offsetTop;parentEl=parentEl.offsetParent;}return [x_offset,y_offset];};
	  
var Try={these : function(){var return_value=null;for(var i=0;i<arguments.length;i++){try{return_value=arguments[i]();break;}catch(e){}}return return_value;}};




/*Drag*/
Number.prototype.NaN0=function(){return isNaN(this)?0:this;}
var iMouseDown  = false;
var dragObject  = null;
var curTarget   = null;

function makeDraggable(item){
 
	if(!item) return;
	item.onmousedown = function(ev){
		dragObject  = this;
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
	
}

function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e     = e.offsetParent;
	}

	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

	return {x:left, y:top};

}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

function mouseDown(ev){
	ev         = ev || window.event;
	
	var target = ev.target || ev.srcElement;

	//if(target.onmousedown || target.getAttribute('DragObj')){
		//return false;
	//}
}

function mouseUp(ev){

	dragObject = null;

	iMouseDown = false;
}


function mouseMove(ev){
	ev         = ev || window.event;
	var target   = ev.target || ev.srcElement;
	var mousePos = mouseCoords(ev);

	if(dragObject){
		dragObject.style.position = 'absolute';
		dragObject.style.top      = mousePos.y - mouseOffset.y;
		dragObject.style.left     = mousePos.x - mouseOffset.x;
	}


	lMouseState = iMouseDown;


	if(curTarget || dragObject) return false;
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup   = mouseUp;


var Browser=new Object();

Browser.isMozilla=(typeof document.implementation!='undefined')&&(typeof document.implementation.createDocument!='undefined')&&(typeof HTMLDocument!='undefined');
Browser.isIE=window.ActiveXObject?true:false;Browser.isGecko=navigator.userAgent.indexOf("Gecko")!=-1;

Browser.isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1);

if(Browser.isMozilla&&!Browser.isOpera){
  HTMLElement.prototype.removeNode=function(){this.parentNode.removeChild(this);}
  }
  
  

// Template 
function ChangeItemStatus(hiddenId,subtitle,value)
{
    var ele=event.srcElement;
//    var button="Radio_"+subtitle;
    var button=subtitle;
   
    if(ele.tagName=="IMG"){
        checkRadio(button,value);
    }
   
    var hidden=getObject(hiddenId);
  
    hidden.value=getCheckboxValue(button);
}
function checkRadio(group,value){

    var i=0;
    var radios=document.forms[0][group];
    if(radios.length==null){radios.checked=true;return;}
    for(i=0;i<radios.length;i++){        
        if(radios[i].value==value){
            if(radios[i].type.toLowerCase()=="radio")
            {
                radios[i].checked=true;
                return;
            }
            else radios[i].checked=!radios[i].checked;
            break;
        }
    }    
}
function getCheckboxValue(group){
    var i=0;
    var temp="";
    var radios=document.forms[0][group];
    
    if(radios.length==null)return radios.value;
    for(i=0;i<radios.length;i++){
        if(radios[i].checked){
            temp+=","+radios[i].value;
        }
    }
    if(temp.lenght<1)return "";
    return temp.substring(1,temp.length);    
}


// Template 
function EvaluateRadioItem(clientId, value,checked)
{
   // var tag=checked?"checked":"radio";
    
    var groups=document.all[clientId].getElementsByTagName("INPUT");
    var i=0;
   
    
    for(i=0;i<groups.length;i++){
     
        if(groups[i].value==value)groups[i].checked=true;
        
    }
    return;
    
}
// Template 
function DisplayDiv(objDiv)
{
    if (document.all[objDiv].style.display == "none")
        document.all[objDiv].style.display = "block";
    else
        document.all[objDiv].style.display = "none";
}
// Template 
function HiddenDiv(objDiv)
{
    document.all[objDiv].style.display = "none";
}

// Template 
function SaveData(objTemplateName, objNewContent)
{
    var txtTemplateName = document.all[objTemplateName].value;
    var txtNewContent = document.all[objNewContent].value;

    var path1=document.location.href+"?action=newtemplate&filename="+txtTemplateName+"&content="+txtNewContent;
//    var strContent = "action=newtemplate&filename="+txtTemplateName+"&content="+txtNewContent;
     
    xmlParserSec = CreateXmlhttp();
    
    getFromXml(xmlParserSec, SaveToResponseClient, path1);
//    postToXml(xmlParserSec, SaveToResponseClient, path1, strContent);    
    
}

// Template 
function UpdateData(fileName, txtTemplateID)
{
    var txtTemplateContent = document.all[txtTemplateID].value;

    var path1 = document.location.href+"?action=updatetemplate&filename="+fileName+"&content="+txtTemplateContent;
//     var strContent = "action=updatetemplate&filename="+fileName+"&content="+txtTemplateContent;
     
    xmlParserSec = CreateXmlhttp();
         
    getFromXml(xmlParserSec, UpdateToResponseClient, path1);
//     postToXml(xmlParserSec, UpdateToResponseClient, path1, strContent);    
    
}

// Template
function SaveToResponseClient()
{
    if(xmlParserSec.readystate==4)
    {
        if(xmlParserSec.status==200)
        {
            document.location.reload();
        }
    }    
}

// Template
function UpdateToResponseClient()
{
    if(xmlParserSec.readystate==4)
    {
        if(xmlParserSec.status==200)
        {
            document.location.reload();
        }
    }    
}

// Template
function UploadTemplateImage(action, objFileControl, newFileName)
{
    var strOldFileName = document.all[objFileControl].value;

    var path1=document.location.href+"?templateimageaction="+action+"&uploadfilename="+escape(strOldFileName)+"&newfilename="+escape(newFileName);
    
    xmlParserSec = CreateXmlhttp();
     
    getFromXml(xmlParserSec, UploadToResponseClient, path1);    
    
}

// Template
function UploadToResponseClient()
{
    if(xmlParserSec.readystate==4)
    {
        if(xmlParserSec.status==200)
        {
//            alert("Upload image successfully");
        }
    }    
}

//Skins
function changeSkins(subTitle, index, imagepath)
{
        document.all["radio_"+subTitle+index].checked=true;
       
       // ChangeHidden(clientID+"_hidValue", document.all["radio_"+subTitle+index].value, "radio_"+subTitle+index, "radio_"+subTitle+index);
   document.all["hidSkinsValue"].value=imagepath;
}

function ShowMore(objChk, objText)
{
    chk = document.all[objChk];
    txt = document.all[objText];
    if (chk == null || txt == null)
    {
        return;
    }
    if (chk.checked)
    {
        txt.style.display="block";
    }
    else
    {
        txt.style.display="none";
    }
}

//Simon
function setGroup(id,divid,titlerow) 
{
    div=getObject(divid);
 
    if(div==null)
    {
        //alert("divid=" + divid);
        //alert("div=" + div);
        return;
    }
  
    if(div.length)div=div[0];
	var lists = div.children; 
	
	for(i=0;i<lists.length;i++) 
	{
		if( lists[i].Category == id)
			lists[i].style.display = "block"; 
		else 
			lists[i].style.display = "none"; 
	} 
	
	var row;
	if(setGroup.arguments.length==2)
	    row= event.srcElement.parentElement; 
	else
	    row=getObject(titlerow);
	 
	
	     
	for(i=0;i<row.cells.length;i++) 
	{ 
		if( row.cells[i].item == id)
		    row.cells[i].style.backgroundColor="#0066CC";
		//	row.cells[i].style.backgroundColor="darkgreen"; 
		else 
		    row.cells[i].style.backgroundColor="#CCCCCC"; 
		//	row.cells[i].style.backgroundColor="#0066cc"; 
	} 

}

// when clicks chk, ctrID will change the status
// ctrID is the target control's id
function changeObjStatusByCheckBox(chk, ctrID)
{
    var control=document.getElementById(ctrID);
    
    if (!control)
        return;
    
    control.readOnly=!chk.checked;
    
    control.className="control_disabled_" + (!chk.checked);
}

function ShowHiddenCategory(num)
{   var frameid="iframe_divMenu"+num;
    var iframe=document.frames[frameid];
    var div=iframe.document.getElementById("divMenu_"+num);
    
    if (iframe.document.body!=null)    
    iframe.document.body.style.margin="0px";
    
    if(!div){
       
        var content='<div id="divMenu_'+num+'" style="height:300px;background-color:White;padding:0px;border:1px solid #7DC2DF;list-style:none;margin-left:0px;font-size:12px;color:black;">[CONTENT]</div>';
        var temp=eval("Content"+num);
        if (temp==null ||temp=="")
            temp="<p style=width:100%;height:300>No Category...</p>";
        content=content.replace("[CONTENT]",temp);
       
        iframe.document.write(content);
//        iframe.document.body.style.margin=0;
    }
//    var objframe=window.document.all[frameid];
        var objframe=window.document.getElementById(frameid);
    
    objframe.style.height=250;
    objframe.style.width=200;
    objframe.style.overflow="auto";
    objframe.style.position="absolute";
    objframe.scrolling="auto";
//    objframe.style.z-index="2999";
    
    if(objframe.style.display!="block")
        objframe.style.display="block";
    else
        objframe.style.display="none";


}
//for CuteEdit GroupImage 2007-1-19

function getImageDiv(editor){
var strContent=editor.getHTML();
return getPart(strContent,"<div class=MutiImage_","</div>") 

}

function getGroupId(editor){
var div=getImageDiv(editor);
if(div==null)return -1;

 var group=getPart(div,"GroupID=",">");

if(group==null)return -1;

var arr=group.split("=");

return arr[1].replace(">","").replace("\"","").replace("\"","");

} 

function showInsertGroupImage(my123)
{
	showModalDialog("/Providers/HtmlEditorProviders/CEHtmlEditorProvider/CuteSoft_Client/CuteEditor/InsertImageLabel.aspx?GroupID=" + getGroupId(CuteEditor_GetEditor(my123)) + "&_rand="+new Date().getTime(),CuteEditor_GetEditor(my123),"dialogWidth:800px;dialogHeight:500px");
}

//Check is number 
function isNumber(oNum)
{
  if(!oNum) return false;
  var strP=/^\d+(\.\d+)?$/;
  if(!strP.test(oNum)) return false;
  try{
      if (parseFloat(oNum)!=oNum) 
        return false;
  }
  catch(ex)
  {
      return false;
  }
  return true;
}


function getObject(elementId) 
{ 
    if (document.getElementById) 
    {
          return document.getElementById(elementId); 
    }
    else if (document.all) 
    {
         return document.all[elementId]; 
    }
    else if (document.layers) 
    { 
    	 return document.layers[elementId]; 
    } 
   
}

//***************************************************
//****************** Shopping Cart ******************
//***************************************************
// Add To Cart
function addToCart(entityID, type)
{
//    var sUrl="/Store/CartServices.aspx";
    var portalID=__portalId;
    var sUrl = "/Store/CartHandler.ashx";
    var destinationUrl = "http://" + __portalAlias;
    
    var addToCartSuccess = function(o){
        if(o.responseText !== undefined){ 
            var strContent = o.responseText;  
            if (strContent.length > 0)
            {
                var indexTabID = strContent.indexOf("|");                
                var tabid = strContent.substring(indexTabID+1, strContent.length);
                        
                switch(tabid)
                {                
                    case "-1":
                        // ParameterError.CannotNull
                        alert(__ParameterError_CannotNull);
                        break;
                    case "-2":
                        // ParameterError.ParameterIsInvalid
                        alert(__ParameterError_ParameterIsInvalid);
                        break;
                    default:
                        var indexTabID = strContent.indexOf("|");
                
                        var tabid = strContent.substring(indexTabID+1, strContent.length);
                       
                        var strMiniCartUrl = "/tabid/" + tabid + "/CartType/" + type;
                        strMiniCartUrl += "/default.aspx";
                        var newWindow = window.open(destinationUrl+strMiniCartUrl, type);
                        newWindow.focus();
                        break;
                }
            }
        }
    }

    var addToCartFailure = function(o){
        if(o.responseText !== undefined){
            //alert(o.statusText+'\r\n'+o.responseText);
        }
    }

    var addToCartCallback =
    {
         success: addToCartSuccess,
         failure: addToCartFailure
    };
    
    YAHOO.util.Connect.asyncRequest("POST", sUrl, addToCartCallback, "portalID="+portalID+"&entityID="+entityID+"&Sender="+type);

}


function createDelegate(oThis, pFunc) 
    {
        return function() {pFunc.apply(oThis, arguments);};
    }
    
function jsTrim(s) {return s.replace(/(^\s+)|(\s+$)/g, "");}


var isIE = navigator.appVersion.indexOf("MSIE")!=-1;
function getscrollHeight(){
   if(document.body.scrollHeight>document.documentElement.clientHeight)
   {
        return document.body.scrollHeight
   }
   else{
        return document.documentElement.clientHeight}};
   


function displayElementsByTag(tagName,isShow,excludeItems){

    var i=0;
    var objects=document.getElementsByTagName(tagName);
  
    for(i=0;i<objects.length;i++){ 
        
        if(!isShow){
           
             if(excludeItems!=null){
                    if(objects[i].id!=null){
                         if(indexOfArray(objects[i].id,excludeItems)>=0){
                              continue;
                         }
                    }
             }
             objects[i].style.display="none";
        }
        else objects[i].style.display="inline";
    }
    
}

function indexOfArray(value,array){
    if(array==null||value==null)return -1;
    var matchCase=false;
    if(indexOfArray.arguments.length=3)matchCase=indexOfArray.arguments[2];
    var i=0;
    for(i=0;i<array.length;i++){
        if(matchCase){
            if(array[i]==value)return i;
        }
        else{
            if(array[i].toLowerCase()==value.toLowerCase())return i;
            
        }
    }
    return -1;
  
}

// Check the strNum 
function IsInteger(strNum) 
{ 
    var integer; 
    try
    {
        integer = parseInt(strNum); 
    }
    catch(e)
    {
    }
    if (isNaN(integer)) 
        return false; 
    else if (integer.toString().length==strNum.length) 
        return true;
    else 
        return false; 
} 

// Check the strNum 
function IsNumeric(strNum) 
{ 
    var f; 
    try
    {
        f = parseFloat(strNum); 
    }
    catch(e)
    {
    }
    
    if (isNaN(f)) 
        return false; 
    else if (f.toString().length==strNum.length) 
        return true;
    else 
        return false; 
} 

function urlEncode(str)
{
	if(str==null||str=="")
		return "";
	var newstr="";
	function toCase(str){
		return str.toString(16).toUpperCase();
	}
	for(var i=0,icode,len=str.length;i<len;i++){
		icode=str.charCodeAt(i);
		if( icode<0x10)
			newstr+="%0"+icode.toString(16).toUpperCase();
		else if(icode<0x80){
			if(icode==0x20)
				newstr+="+";
			else if((icode>=0x30&&icode<=0x39)||(icode>=0x41&&icode<=0x5A)||(icode>=0x61&&icode<=0x7A))
				newstr+=str.charAt(i);
			else
				newstr+="%"+toCase(icode);
		}
		else if(icode<0x800){
			newstr+="%"+toCase(0xC0+(icode>>6));
			newstr+="%"+toCase(0x80+icode%0x40);
		}
		else{
			newstr+="%"+toCase(0xE0+(icode>>12));
			newstr+="%"+toCase(0x80+(icode>>6)%0x40);
			newstr+="%"+toCase(0x80+icode%0x40);
		}
	}
	return newstr;
};

function urlDecode(str){
	if(str==null||str=="")
		return "";
	var newstr="";
	function toCase(sstr){
		return sstr.tostring(16).toUpperCase();
	}
	for(var i=0,ichar,len=str.length;i<len;){
		if(str.charAt(i)=="%"){
			ichar=str.charAt(i+1);
			if(ichar.toLowerCase()=="e"){
				newstr+=String.fromCharCode((parseInt("0x"+str.substr(i+1,2))-0xE0)*0x1000+(parseInt("0x"+str.substr(i+4,2))-0x80)*0x40+parseInt("0x"+str.substr(i+7,2))-0x80);
				i+=9;
			}
			else if(ichar.toLowerCase()=="c"||ichar.toLowerCase()=="d"){
				newstr+=string.fromCharCode((parseInt("0x"+str.substr(i+1,2))-0xC0)*0x40+parseInt("0x"+str.substr(i+4,2))-0x80);
				i+=6;
			}
			else{
				newstr+=String.fromCharCode(parseInt("0x"+str.substr(i+1,2)));
				i+=3;
			}
		}
		else{
			newstr+=str.charAt(i).replace(/\+/," ");
			i++;
		}
	}
	return newstr;
};








var Browser=new Object();

Browser.isMozilla=(typeof document.implementation!='undefined')&&(typeof document.implementation.createDocument!='undefined')&&(typeof HTMLDocument!='undefined');
Browser.isIE=window.ActiveXObject?true:false;Browser.isGecko=navigator.userAgent.indexOf("Gecko")!=-1;

Browser.isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1);

if(Browser.isMozilla&&!Browser.isOpera){
  HTMLElement.prototype.removeNode=function(){this.parentNode.removeChild(this);}
  }


function getParent(tag,node){
    if (node==null)
        return node;
    if(node.tagName.toUpperCase()==tag.toUpperCase())return node;
    if("BODY"==node.tagName.toUpperCase())return null;
    if (node.parentNode==null)
        return node;
    node=node.parentNode;
    return getParent(tag,node);
}
function getParentByClass(classes,node){
    if (node==null)
        return node;
    if(node.className.toUpperCase()==classes.toUpperCase())return node;
    if("BODY"==node.tagName.toUpperCase())return null;
    if (node.parentNode==null)
        return node;
    node=node.parentNode;
    return getParentByClass(tag,node);
}
		  
function CreateXmlhttp(){
		var xmlhttp = null;
		try{
			xmlhttp = new ActiveXObject('MSXML2.XMLHTTP'); 
			return xmlhttp;
		}
		catch(e){}
		try{
			xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');		
			return xmlhttp;
		}
		catch(e){} 
		return null;
		}
		
function XmlGet(paras,objResponseFunction,objResponse){
    var url=document.location.href;
  
    url=url.replace("#","");
    if(url.indexOf("?")>0)url+="&"+paras;
    else url+="?"+paras;
    var xml=CreateXmlhttp();
    url=url+"&Randomitem=" + Math.random();

	try{ 
	    xml.open("Get",url,true); 
	    xml.onreadystatechange=function(){
	     
	        if(objResponseFunction==null)return;
	     	if(xml.readyState == 4){ 
	              
  					if(xml.status == 200)
					{ 
					    objResponse=xml.responseText;
					    window.setTimeout(objResponseFunction,100);
					}
	        }
	    }
	    xml.send(); 
	}
	catch(e){
	  
	}       
}

function getFromXml(xml,callback,url){
    url=url.replace("#","");
	try{ 
	    xml.open("Get",url+"&Randomitem=" + Math.random(),true); 
	    xml.onreadystatechange=callback;
	    xml.send(); 
	}
	catch(e){
	
	}       
}