var iChars = "~|\'\"";
var dHeight;


function checkNewsItems(newsUrl,panelId,newsName,OfficeID,newsPos,total) {
	
	document.newsForm.newsUrl.value = newsUrl;
	document.newsForm.newsName.value = newsName;
	var OfficeID = (OfficeID != undefined) ? OfficeID : "";
	
	var flag = 0;
	for(var i=0;i<total;i++) {
		if($("mynews-dd-panel"+i).innerHTML != "")
		flag = 1;
	} 
	if((flag==1)&&($("mynews-dd-panel"+panelId).id==$('openID').value)) { 
		for(var j=0; j<total; j++) {
			$("mynews-dd-panel"+j).innerHTML = "";
		}
		if(isIE){
		window.frameElement.height = window.frameElement.contentWindow.document.body.scrollHeight-12;
		}
		else if(navigator.userAgent.indexOf("Safari") > 0){
			window.frameElement.height = dHeight; 
		}
		else
		window.frameElement.height = window.frameElement.contentWindow.document.body.scrollHeight;
		$('mynews-dt-img'+panelId).src = "/tpl/rsft/images/expand_open.gif";
	}
	else {
		dHeight = window.frameElement.contentWindow.document.body.scrollHeight;
		var loadingPanel = "mynews-dd-panel"+panelId;
		var i			= Math.round(10000*Math.random());
		var url			= '/php/widgets/news/include.ajax';
		if($('fromCP')) 
		var pars		= "?newsUrl="+newsUrl+"&panelId="+panelId+"&OfficeID="+OfficeID+"&i="+i+"&newsPos="+newsPos+"&user_ID="+$('user_ID').value+"&fromCP&itemNo="+$('itemNo').value;
		else
		var pars		= "?newsUrl="+newsUrl+"&panelId="+panelId+"&OfficeID="+OfficeID+"&i="+i+"&newsPos="+newsPos+"&user_ID="+$('user_ID').value+"&itemNo="+$('itemNo').value;
		var onLoading	= function() {
			$I(loadingPanel,"<center><img src='/tpl/rsft/images/loading.gif' /></center>");
		}
		var onComplete	= function(responseText) { //alert(responseText);
			$I(loadingPanel,responseText);
			window.frameElement.height = window.frameElement.contentWindow.document.body.scrollHeight;
			$('openID').value=loadingPanel;
			$('mynews-dt-img'+panelId).src = "/tpl/rsft/images/expand_close.gif";
			for(var i=0;i<total;i++) {
				if(i!=panelId)
				$('mynews-dt-img'+i).src = "/tpl/rsft/images/expand_open.gif";
			} 
		}
		MyAjax.get(url+pars,onComplete,onLoading);
	}
}

function popupNews(destination,params) { 
	//var obj = top.window.$("loadedIframemodule_mynews_content").Document || top.window.$("loadedIframemodule_mynews_content").contentDocument;	
	//var obj = top.window.$("NewsIframe").Document || top.window.$("NewsIframe").contentDocument;	
	switch(destination) {
		case "displayall" :
		pageUrl		= '/php/widgets/news//displayall.php?newsUrl='+document.newsForm.newsUrl.value+"&"+params;
		title		= 'My News';
		tabTitle	= Base64.decode(document.newsForm.newsName.value);
		break;
	}	top.window.winPop.open({'title':title,'target':'rz_mynews','width':WIN_POP_WIDTH,'height':WIN_POP_HEIGHT,'page_height':WIN_POP_PAGE_HEIGHT,'page_width':WIN_POP_PAGE_WIDTH,'tab_1_title':tabTitle,'page_url':pageUrl});
	//top.window.winPop.open(pageUrl,title,tabTitle);
}

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=.@\'\"",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function popupDetailNews(OfficeID,itemID) {
	var i		= Math.round(10000*Math.random());
	var url		= '/controlpanel/myoffice/include.ajax';
	var pars	= "mode=getOfficeNewsName&OfficeID="+OfficeID+"&i="+i;
	var onComplete = function(responseText) {
		var newsName = responseText;
		top.window.winPop.open({'title':newsName,'target':'lz_myoffice','width':WIN_POP_WIDTH,'height':WIN_POP_HEIGHT,'page_width':WIN_POP_PAGE_WIDTH,'page_height':WIN_POP_PAGE_HEIGHT,'tab_1_title':'View Detail','page_url':'/controlpanel/myoffice/viewdetail.php?OfficeID='+OfficeID+'&itemID='+itemID});
	}
	MyAjax.post(url,pars,onComplete);	
}

function setIframeHeight(iframe) {
	//if (iframe.contentWindow.document.body.scrollHeight>0) {
			var _resize = function () {
				iframe.height = iframe.contentWindow.document.body.scrollHeight;
			};
			setTimeout(_resize, 700);

		//iframe.height = iframe.contentWindow.document.body.scrollHeight;
		//	if(iframe.id=="NewsIframe")
		//	$('iframeHeight').value=iframe.contentWindow.document.body.scrollHeight;
	//}
}

function iniIframeHeight(iframe,divID) { 
			
			var _resize = function () {
				iframe.height = iframe.contentWindow.document.body.scrollHeight;
				$(divID.id).style.display="none";
				
			};
			setTimeout(_resize, 700);
}

function initIframeHeight(iframe,divID) { 
	if(iframe.id.indexOf("SearchIframe")=='-1') {
		iframe.height = iframe.contentWindow.document.body.scrollHeight;
//		$(divID.id).style.display="none";
	}
	else {
		if(divID.id.indexOf("lLoading")!='-1')
			iframe.height = 350;
		else
			iframe.height = 390;
	}	
	$(divID.id).style.display="none";
}


var winPop = function(){
var win;
    
	return {
        init : function(){},
       resetStatus:function() {},
		open : function(pars){ 
            if(!win){ 
				win = new YAHOO.ext.BasicDialog("rsft_win", { 
				modal:true,	autoTabs:true,width:10,	height:10,shadow:false,minWidth:10,minHeight:10,proxyDrag: false,resizable: false,draggable: false,constraintoviewport: true,fixedcenter:true
				});
            }
				
			$('rsft_win_title').innerHTML = pars['title'];
			
				win.resizeTo(pars["width"],pars["height"]);

				var tabs = win.getTabs();
				tabs.getTab(0).setText(pars["tab_1_title"]);

				win.show();
				loadPage(pars['page_url'],"rsft_win_body", {"width":pars["page_width"],"height":pars["page_height"]});
			
        },
		close:function(){win.hide();}
    };
}();


function checkDefaultValue(obj,mode) {
		if(obj.id.indexOf("_")!=-1)
		//var temp = obj.id.substr(obj.id.indexOf("_"));
		var temp = obj.id.substr(0,obj.id.indexOf("_"));
		else
		var temp = obj.id;
		switch(mode) {
			case 'f' : // onFocus
				if((obj.value == $(temp+"Value").innerHTML)&&(obj.style.color == '#999999')) {
					obj.value = '';
					obj.style.color = '#000000';

				}
			break;
			case 'b' : // onBlur
				if(obj.value == '') {
					obj.value = $(temp+"Value").innerHTML;
					obj.style.color = '#999999';
				}
			break;
		}
	}
	
	function customizeRss(rss) {

		var rssDiv = rss.parentNode.parentNode; 
		var d = rssDiv.getElementsByTagName("div"); 
		if (rss.checked){
			//get max div number
			var n=0;
			for(var i=0;i<d.length;i++) {
				n = Math.max(n,parseInt(d[i].id.substr(13)));
			}
			n++; 
			var newRss = document.createElement("div");
			newRss.setAttribute("id","customRssDiv_"+n);			
			newRss.setAttribute("align","left");
			newRss.innerHTML = "<input type='checkbox' name='customSource"+n+"' id='customSource"+n+"' class='checkbox1' onClick='customizeRss(this);'><font face='Verdana' size='2'>  &nbsp;Custom RSS Feed  "+n+" </font><br>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type='text' name='customRssName_"+n+"' id='customRssName_"+n+"' size='20' value='Name' onFocus=\"checkDefaultValue(this,'f');\" onBlur=\"checkDefaultValue(this,'b');\" style='font-size: 10px; font-family: Verdana; color:#999999;'> <input type='text' name='customRssURL_"+n+"' id='customRssURL_"+n+"' size='20' value='URL' onFocus=\"checkDefaultValue(this,'f');\" onBlur=\"checkDefaultValue(this,'b');\" style='font-size: 10px; font-family: Verdana;color:#999999;'>";
			$('totleCustomSource').value = n;
			rssDiv.appendChild(newRss);
		}else{
			//remove last unchecked one
			for(var i=d.length-1;i>-1;i--) {
				var a = d.length-1;
				if (!(d[i].firstChild.checked)){
					rssDiv.removeChild(d[a]);
					$('totleCustomSource').value = d.length;
					break;
				};
			}
		}
	}
	

	function submitRSSSource(close) { 
		//var f		= document.newsSettingsForm;
		var rss		= "";
		var custom	= "";
		var temp	= "";
		var val		= "";
		var check	= 0;
		var obj	= top.window.$("loadedIframecpWin1_tab_1").Document || top.window.$("loadedIframecpWin1_tab_1").contentDocument;
		//alert(obj.getElementById('title').value); 
		if(isEmpty(obj.getElementById('title').value)||(obj.getElementById('title').value=="Enter Title")) {
			alertMessage.show({msg:"Please enter title"},obj.getElementById('title'));
			return false;
		}
		
		for(i=0; i<obj.getElementById('totleSource').value; i++) {
			if(obj.getElementById('newsSource'+i).checked == true) {
				temp = obj.getElementById('newsSource'+i).value + ",";
				rss += temp;
				check = 1;
			}
		}
		obj.getElementById('rss').value	= (rss.substr((rss.length-1),(rss.length)) == ",") ? rss.substr(0,(rss.length-1)) : rss;

		for(i=1; i<=obj.getElementById('totleCustomSource').value; i++) {
			if(obj.getElementById('customSource'+i).checked == true) {
				if(isEmpty(obj.getElementById('customRssName_'+i).value) || obj.getElementById('customRssName_'+i).value == "Name") {
					alertMessage.show({msg:"Please input Custom Rss Name "},obj.getElementById('customRssName_'+i)); 
					return false;
				}else {
				  var tempChars = iChars.replace("\'","");
				  tempChars = tempChars.replace("\"",""); 
				  for (var j = 0; j < obj.getElementById('customRssName_'+i).value.length; j++) {
					if (tempChars.indexOf(obj.getElementById('customRssName_'+i).value.charAt(j)) != -1) {
						alertMessage.show({msg:"Your Custom Rss Name has special characters. \nThese are not allowed.\n Please remove them and try again."},obj.getElementById('customRssName_'+i)); 
						return false;
					}
				  }
				}
				if(isEmpty(obj.getElementById('customRssURL_'+i).value) || obj.getElementById('customRssURL_'+i).value == "URL"){
					alertMessage.show({msg:'Please input Custom Rss URL',adjustX:-22},obj.getElementById('customRssURL_'+i));
					return false;
				}else {
				  for (var j = 0; j < obj.getElementById('customRssURL_'+i).value.length; j++) {
					if (iChars.indexOf(obj.getElementById('customRssURL_'+i).value.charAt(j)) != -1) {
						alertMessage.show({msg:"Your Custom Rss URL has special characters. \nThese are not allowed.\n Please remove them and try again."},obj.getElementById('customRssURL_'+i)); 
						return false;
					}
				  }
				}
				if(obj.getElementById('customRssURL_'+i).value.indexOf("&")!=-1) {
					val = obj.getElementById('customRssURL_'+i).value;
					var arr = val.split('&');
					var counter = 0;
					while (counter<arr.length) {
						counter = counter+1; 
						val = val.replace('&', '*^^*');
					}
					temp	= obj.getElementById('customRssName_'+i).value + "~" + val + ",";
				}
				else {
					temp	= obj.getElementById('customRssName_'+i).value + "~" + obj.getElementById('customRssURL_'+i).value + ",";
				}
				//temp	= obj.getElementById('customRssName_'+i).value + "~" + obj.getElementById('customRssURL_'+i).value + ",";
				//temp	= obj.getElementById('customRssName_'+i).value + "~" + val + ",";
				custom += temp;
				check = 1;
			}
		}
		obj.getElementById('custom').value	= (custom.substr((custom.length-1),(custom.length)) == ",") ? custom.substr(0,(custom.length-1)) : custom;

		if(!check) { 
			alert("Please Choose News Sources");
			//alertMessage.show({msg:"Please Choose News Sources",adjustX:40,adjustY:35},obj.getElementById('number')); 
			obj.getElementById('number').focus();
			return false;
		}

		var pars	= "newsTitle="+obj.getElementById('title').value+"&newsRss="+obj.getElementById('rss').value+"&newsNumber="+obj.getElementById('number').value+"&newsCustom="+obj.getElementById('custom').value; 
		//top.PostDataToFlash('Content',escape(pars));
		top.PostDataToFlash('Content',pars);
		if(close==1) {
			top.SaveWidget();
//			top.window.winPop.close();
//			top.RequestHome();
		}
	}