// iSite3 Common Javascript Utils
// by Nikola Ratkovic 2005,2006
//

this.PMISITE_DisplayCtrl = null;

function PMISITE_HideDisplayCtrl(sender){
	
	if (PMISITE_DisplayCtrl != null){
		if (PMISITE_DisplayCtrl.style.visibility=='hidden'){
			PMISITE_DisplayCtrl.style.visibility='visible'
		}else{
			if (PMISITE_DisplayCtrl.style.visibility=='visible'){
				PMISITE_DisplayCtrl.style.visibility='hidden'
			}
				
		}
		
	}
}
this.PMISITE_HideDisplayCtrl = PMISITE_HideDisplayCtrl;

function PMISITE_CreateDisplayCtrl(){
	var body  = document.getElementsByTagName('body')[0];
	if (body != null){
		var divPlaceholder = document.createElement('div');
		
		with (divPlaceholder){
			id='divLogPlc';
			style.visibility='visible';
			style.position = 'absolute';
			style.overflow = 'scroll';
			style.zIndex='10000';
			style.top = '40px';
			style.left ='40px';
			style.backgroundColor='#ffffff';
			style.width = (parseInt(screen.availWidth)/2) + 'px';
			style.height = (parseInt(screen.availHeight)/2) + 'px';
			onclick = PMISITE_HideDisplayCtrl;
			
			innerText = outerHTML;
			
		}
		var divBtn = document.createElement('div');
		
		with (divBtn){
			id='divLogBtn';
			style.visibility='visible';
			style.position = 'absolute';
			style.zIndex='999';
			style.top = '0px';
			style.left ='0px';
			style.backgroundColor='#ff0000';
			style.width = '48px';
			style.height = '24px';
			innerHTML = '[LOG]';
			onclick = PMISITE_HideDisplayCtrl;
						
		}
		body.appendChild(divBtn);
		body.appendChild(divPlaceholder);
		
		return divPlaceholder;
	}
	
}

this.PMISITE_CreateDisplayCtrl = PMISITE_CreateDisplayCtrl;

function PMISITE_Display(text){
	if (this.PMISITE_DisplayCtrl == null){
		this.PMISITE_DisplayCtrl=PMISITE_CreateDisplayCtrl();
	}
	if (this.PMISITE_DisplayCtrl.style.visibility =='hidden'){
		this.PMISITE_DisplayCtrl.style.visibility =='visible'
	}
	with (this.PMISITE_DisplayCtrl){
		innerHTML += text + '<br>';
	}

}


function PMISITE_NavigateUrl(url, target){
	
	if ((target!= null) && (target!='')){
		var finalUrl = url + "#" + target;
		window.navigate(finalUrl);
	}
	else{
		window.navigate(url);
	}
}

// fired when clicked on item of ultra web list bar 
function PMISITE_ListBarItmBefSelected(oListbar, oItem, oEvent){
	PMISITE_ListBarItmClick(oListbar, oItem, oEvent, 'itmBefore');
}

function PMISITE_ListBarItmAftSelected(oListbar, oItem, oEvent){
	PMISITE_ListBarItmClick(oListbar, oItem, oEvent, 'itmAfter');
}
function PMISITE_ListBarItmClick(oListbar, oItem, oEvent, evName){
	
	if (oItem == null) {
		
		return;
	}
	
	if (oItem.Key == 'GoBack'){
		oEvent.cancel = true;
		PMISITE_GoBack();
	}
	else{
		
		var url = new String((oItem.Tag!=null) ? oItem.Tag : oItem.TargetUrl);
		var target = new String(oItem.TargetFrame);
		
		if ((url != null) && (url != '') && url.indexOf("javascript:")<0){
			var strUrl = new String(url);
			if (strUrl.indexOf("?")<0){
				url += "?rUrl=" + escape(this.PMISITEGLOBALS["CURRENTPAGEURL"]);
			}else{
				url += "&rUrl=" + escape(this.PMISITEGLOBALS["CURRENTPAGEURL"]);
			}
			
			oItem.TargetUrl = url;
			
			if (target.toLowerCase()!='_new'){
				
				window.navigate(url);
			}
			
		}
		else{
			
			oItem.TargetUrl = url;
			if (url != null){
				if ((evName=='itmAfter') && (url.indexOf('javascript:')>-1)){
					var arr=url.split(":");
					if (arr.length > 1){
						eval(arr[1]);
					}	
				}
			}
			
		}
		
	}
	
	
}

function PMISITE_ListBarGrpBefSelected(oListbar, oItem, oEvent){
	PMISITE_ListBarItmClick(oListbar, oItem, oEvent, 'grpBefore');
}

function PMISITE_GoBack_Callback(ret){
	if ((ret!=null) && (ret.error == null)){
		if (ret.value != null){
			
			window.location.href = ret.value;
		}
		
	}
}


function PMISITE_GoBackHandler(oListbar, oItem, oEvent){
	if ((oItem != null) && (oItem.Key == 'GoBack')){
		oEvent.cancel = true;
		PMISITE_GoBack();
	}
}


function PMISITE_GoBack(){
	var url = this.PMISITEGLOBALS["CURRENTPAGEURL"];
	var ret = NavigationHelper.CS_History_ReturnBack(url, PMISITE_GoBack_Callback);
}

function PMISITE_GoToUrlHandler(sender, caption, index, url, tag){
	//alert('going back');
	if ((url != null) && (url != '')){
			var strUrl = new String(url);
			
			if (strUrl.indexOf("?")<0){
				url += "?rUrl=" + escape(this.PMISITEGLOBALS["CURRENTPAGEURL"]);
			}else{
				url += "&rUrl=" + escape(this.PMISITEGLOBALS["CURRENTPAGEURL"]);
			}
	
	}
	window.navigate(url);
	
}

function PMISITE_GoToUrl(url){
	//var ret = NavigationHelper.CS_History_Push(url, PMISITE_GoToUrl_Callback);
}
function PMISITE_GoToUrl_Callback(ret){
	if (ret.error == null){
		if (ret.value != null){
			window.navigate(ret.value);
		}
		
	}
}

function PMISITE_KeyValuePair(key, value){
    this.Key = key;
    this.Value = value;        
}
/* Smart Picture Manager*/
function PMISITE_SmartPicture(img, ftb){
    this.DEF_SP_PARAM = 'sp';
    this.DEF_SP_URL_ID = '::isite::sp::a::';
    this.DEF_SP_IMG_ID = '::isite::sp::img::';
    this.Image = img;
    this.ParentAnchor = null;
    this.ImageUrl = null;
    this.AnchorUrl = null;
    this.IsSmartPicture = false;
    this.ImgIsSmart = false;
    this.AnchorIsSmart = false;
    this.UrlIsSmart=false;
    this.Initialize();
}

PMISITE_SmartPicture.prototype.Initialize = function (){
    this.IsSmartPicture = this.DetectSmartPicture();

}

PMISITE_SmartPicture.prototype.DetectSmartPicture = function (){
    var parentNode = this.Image.parentNode;
    var img_flag = false;
    var a_flag = false;
    var url_flag = false;
    img_flag = ((this.Image.name!=null) && (this.Image.name.indexOf(this.DEF_SP_IMG_ID)>=0)); 
    
    this.ImageUrl = new PMISITE_Url(this.Image.src);
                
               
    if (parentNode == null){
        return false;
    }
    else{
    
        if ((parentNode.nodeType ==1) && (parentNode.tagName.toLowerCase() == 'a')){
            
            this.ParentAnchor = parentNode;
            a_flag = ((parentNode.name!=null) && (parentNode.name.indexOf(this.DEF_SP_URL_ID)>=0)); 
            if (a_flag){
                this.ParentAnchor = parentNode;
                
                
            }
        }
    }
    this.ImgIsSmart = img_flag;
    this.AnchorIsSmart = a_flag;
    this.UrlIsSmart = url_flag;
    
    return (a_flag && img_flag);
}

PMISITE_SmartPicture.prototype.CreateSmartPicture = function() {
    var width= parseInt(this.Image.style.width);
    var height = parseInt(this.Image.style.height);
    var height
    // create smartpicture params
    var tms_value = width + 'x' + height;
    this.ImageUrl.SetParam('sp', tms_value);
    this.ImageUrl.RemoveParam('tms');
    this.ImageUrl.RemoveParam('rUrl');
    
    this.Image.src = this.ImageUrl.RebuildUrl();
    this.AnchorUrl = new PMISITE_Url(this.Image.src);
    this.AnchorUrl.RemoveParam('sp');
    var imgParent = null;
    if (this.ParentAnchor == null){
        imgParent = this.Image.parentNode;
        this.Image.name = this.DEF_SP_IMG_ID;
        this.ParentAnchor = imgParent.ownerDocument.createElement('a');
        this.ParentAnchor.name = this.DEF_SP_URL_ID;
        
       
        this.ParentAnchor.href = this.AnchorUrl.RebuildUrl();
        this.ParentAnchor.target = '_blank';
        
        //replacing image with anchor (a)
        var replacedEl = imgParent.replaceChild(this.ParentAnchor, this.Image);
        // appending img to anchor 
        this.ParentAnchor.appendChild(this.Image);
        
    }else{
        this.ParentAnchor.removeAttribute('onclick');
        this.ParentAnchor.href = this.AnchorUrl.RebuildUrl();
        this.ParentAnchor.target = '_blank';
        this.ParentAnchor.name = this.DEF_SP_URL_ID;
        this.Image.name = this.DEF_SP_IMG_ID;
    }
   
}

PMISITE_SmartPicture.prototype.RemoveSmartPicture = function() {
    
    
    // removing smart picture attributes
    this.ImageUrl.RemoveParam('tms');
    this.ImageUrl.RemoveParam('rUrl');
    //remove sp (SmartPicture) element
    this.ImageUrl.RemoveParam('sp');
    this.Image.name.replace(this.DEF_SP_IMG_ID, '');
    this.Image.src = this.ImageUrl.RebuildUrl();
    this.IsSmartPicture = false;
    //removing parent link
    if (this.ParentAnchor != null){
        var parent = this.ParentAnchor.parentNode;
        this.ParentAnchor.removeChild(this.Image);
        parent.replaceChild(this.Image, this.ParentAnchor);
        this.ParentAnchor = null;
    }
    
   
}

PMISITE_SmartPicture.prototype.Update = function(pwidth, pheight, src) {
    
    if (this.IsSmartPicture){
        var width= parseInt(pwidth);
        var height = parseInt(pheight);
        
        // create smartpicture params
        var tms_value = width + 'x' + height;
        this.ImageUrl.SetParam('sp', tms_value);
        this.ImageUrl.RemoveParam('tms');
        this.ImageUrl.RemoveParam('rUrl');
        this.Image.src = this.ImageUrl.RebuildUrl();
    }
   
}

/* Url Manager */
function PMISITE_Url(url){
    
    
    this.Url = url;
    this.Schema='';
    this.Host ='';
    this.Port = -1;
    this.Path ='';
    this.AddressPart = '';
    this.ParamsPart='';
    this.QueryParams = new Array();
    
    this.Initialize();

}

PMISITE_Url.prototype.DetectSchema= function (){

        var SUPPORTED_SCHEMAS = new Array('http://','https://','ftp://','sftp://','mailto:');
        var url = new String( this.Url.toLowerCase());
        for (i=0;i<SUPPORTED_SCHEMAS.length;i++){
          if ( url.indexOf(SUPPORTED_SCHEMAS[i],0) >=0){
            this.Schema = SUPPORTED_SCHEMAS[i];
            return true;
          }
        }
            
       return false;
    }
    
PMISITE_Url.prototype.ParseQueryParams = function (paramsPart){
  var result= new Array();
  
  if ((paramsPart == null) || (paramsPart == '')){
        return null;
  }
  var params = paramsPart.split('&');
  
  
  if ((params != null) && (params.length >0)){
      for ( var i =0; i<params.length; i++){
            var items = params[i].split('=');
            var name='';
            var value = '';
            if (items.length>0){
                name = items[0];
                if (items.length>1){
                    value = items[1];
                    
                    result[i]= new PMISITE_KeyValuePair(name, value);
                    
                }
                                                            
            }                
      }
  }
 return result;     
}
    
PMISITE_Url.prototype.DecodeParams = function (){
    
    var url = new String( this.Url);
    var urlArray = url.split('?');
    if (urlArray.length >0){
        this.AddressPart = urlArray[0];
        if (urlArray.length>1){
            this.ParamsPart = urlArray[1];
            this.QueryParams=this.ParseQueryParams(this.ParamsPart);
        }
    }
    
    
}
    
PMISITE_Url.prototype.RebuildUrl = function (){
    var url = new String();
    if (this.Schema != ''){
        url += this.Schema;
        url += this.Host;
        url += '/';
    }
    url += this.Path;
    
    if (this.QueryParams.length>0){
        url+='?';
    }
    
    for (var i=0;i<this.QueryParams.length;i++){
        var item = this.QueryParams[i];
        url += escape(item.Key) + '='+ escape(item.Value);
        if (i<(this.QueryParams.length-1)){
           url +='&';
        }
    }
    return url;                     
}
    
    
    
    
PMISITE_Url.prototype.DetectHostAndPath = function (){
    var url = (new String(this.Url)).toLowerCase();
    // removing schema part
    var cUrl = '';
    if (this.Schema != '' ){
        cUrl = this.AddressPart.substr(this.Schema.length, (this.AddressPart.length-this.Schema.length));
    }
    else{
        cUrl = this.AddressPart;
    }
    
    if ((cUrl != null) && (cUrl != '') && (cUrl.indexOf('/')>0)){
        var pathParts = cUrl.split('/');
        if (pathParts.length>0){
            if (this.Schema != ''){
                // if schema exists then, host exists
                this.Host = pathParts[0];
                if (pathParts.length>1){
                    pathParts.shift();
                    this.Path = pathParts.join('/');
                }
            }
            else{
              // if schema does not exists then host does not exist
                 this.Path = pathParts.join('/');
            }
            
            
        }
        
        
        
    }
    
}

PMISITE_Url.prototype.ContainsParam = function (name){
    return (this.IndexOfParam(name)>=0);
}


PMISITE_Url.prototype.IndexOfParam = function (name){
    for (var i=0;i<this.QueryParams.length;i++){
        if (this.QueryParams[i].Key == name){
            return i;
        }
    }
    return -1;
}

PMISITE_Url.prototype.SetParam = function(name,value){
   var index = this.IndexOfParam(name);
   if (index>=0){
        this.QueryParams[index].Value = value;
        return this.QueryParams[index];
   }
   else{
        index = this.QueryParams.length;
        this.QueryParams[index] = new PMISITE_KeyValuePair(name,value);
        return this.QueryParams[index];
   }
   
}

PMISITE_Url.prototype.GetParam = function (name){

   var index = this.IndexOfParam(name);
   if (index>=0){
        this.QueryParams[index].Value = value;
        return this.QueryParams[index];
   }else{
        return null;
   }
   
}

PMISITE_Url.prototype.RemoveParam = function (name){

   var index = this.IndexOfParam(name);
   if (index>=0){
        this.QueryParams.splice(index,1);
        return index;
   }else{
        return -1
   }
   
}

PMISITE_Url.prototype.Initialize = function (){
    this.DecodeParams();
    this.DetectSchema();
    this.DetectHostAndPath();
}
/* Combines two urls */
function PMISITE_UrlCombine(part1, part2){
    var cleanPart1;
    var cleanPart2;
    var p2BeginIndex;
    var i=0;
    var finalPath= new String('');
    var s = new String();
    
    if ((part2!= null) && (part2!='')){
            for (i = 0; i<part2.length;i++){
                var c = part2.charAt(i);
                if (c != '/'){
                    break;
                }
            }
     }
     cleanPart2 = part2.substr(i);
     part1 = part1.replace(':/', '[%dot%slash%]');
     if ((part1!=null) && (part1!='')){
            var c;
            for (i = part1.length - 1; i>0; i--){
                c = part1.charAt(i);
                if (c != '/'){
                    break;
                }
            }
            if (i > 0){
                i += 1;
            }
            
            cleanPart1 = part1.substr(0, i);
        }
        if (cleanPart1 != ''){
            finalPath = cleanPart1 + '/';
        }
        if (cleanPart2 != ''){
            finalPath += cleanPart2;
        }
        finalPath = finalPath.replace("[%dot%slash%]", ":/");
        if ((part1=='/') && (finalPath.charAt(0) != '/')){
            finalPath = '/' + finalPath;
        }
        return finalPath
}


function PMISITE_OpenImporterDialog(url, name){
				
		var ROOT = this.PMISITEGLOBALS['ROOTPATH'];
		if (url==null){
		    url = this.PMISITEGLOBALS['IMPORT_DIALOG_URL'];
		}
		var windowPath = PMISITE_UrlCombine(ROOT, url);
		var dlg= window.open( windowPath , "IMPORT_DIALOG" + name, "width=550, height=450, location=no, menubar=no, status=no, toolbar=no, scrollbars=no, resizable=no");
		return dlg;
}
this.PMISITE_OpenImporterDialog = PMISITE_OpenImporterDialog;
