
/***********************************************
* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

/*
 * Aux functions
 */

//IE Browser test
var IE = document.all?true:false;

String.prototype.trim = function() {
		var nstr = this.replace(/^\s+/, '');
		for (var i = nstr.length - 1; i >= 0; i--) {
			if (/\S/.test(nstr.charAt(i))) {
				nstr = nstr.substring(0, i + 1);
				break;
			}
		}
		return nstr;
}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	){
		var strText = this;
		var intIndexOfMatch = strText.indexOf( strTarget );
 
		// Keep looping while an instance of the target string
		// still exists in the string.
		while (intIndexOfMatch != -1){
			// Relace out the current instance.
			strText = strText.replace( strTarget, strSubString )
 
			// Get the index of any next matching substring.
			intIndexOfMatch = strText.indexOf( strTarget );
		}
 
		// Return the updated string with ALL the target strings
		// replaced out with the new substring.
		return( strText );
}

String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}

 /** @return true if is a string */
 function isString(object) {
      return typeof object == "string";
 }

function eventPush(obj, event, handler) {
  var handlerwrapper = function(e) {	
	if( !e ) {
	    //if the browser did not pass the event information to the
	    //function, we will have to obtain it from the event register
	    if( window.event ) {
	      //Internet Explorer
	      e = window.event;
	    } else {
	      //total failure, we have no way of referencing the event
	      return;
	    }
	 }
	if (IE)	{
		//alert(this.event.srcElement);
		handler(this.event.srcElement,e);
	} else {
		handler(this,e);
	}
  }
  if (obj.addEventListener) {
    obj.addEventListener(event, handlerwrapper, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('on'+event, handlerwrapper);
  }
}

function eventPushInsideiFrame(obj, event, handler) {
  var handlerwrapper = function(e) {	
	if( !e ) {
	    //if the browser did not pass the event information to the
	    //function, we will have to obtain it from the event register
	    if( window.event ) {
	      //Internet Explorer
	      e = window.event;
	    } else {
	      //total failure, we have no way of referencing the event
	      return;
	    }
	 }
	if (IE)	{
		handler(e);
	} else {
		handler(e);
	}
  }

  if (obj.addEventListener) {
    obj.addEventListener(event, handlerwrapper, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('on'+event, handlerwrapper);
  }
}

function max(n1,n2) {
	if (n1>n2) return n1; else return n2;
}
function min(n1,n2) {
	if (n1<n2) return n1; else return n2;
}

auxiallaryjs = new Array();
auxiallaryjs[0] = "js/jquery-1.4.1.js"
auxiallaryjs[1] = "js/iframeresize.js"

//contruct an iframe inside div
//this will automatically retrieve and set the name of iframe as well
function constructTargetableIFrame(template, srcname,indiv,frameborder) {
    var width = "100%";
    var name = srcname;
    var iframeid = template + uniqueNumber();
    if (name == undefined) name = "none";
    indiv.innerHTML = '<div name="' + name + '" id="' + iframeid + '" style="overflow:none;width:' + width +  '"></div>';
    var iframe = document.getElementById(iframeid);
	iframe.src= function(url) { loadhtml(iframe, url) };
    return iframe;
}

function addscopedhtml(scope,container,html,oncomplete) {
	container.innerHTML = html;
	var begindivtagindex = 0;
	while((begindivtagindex = html.indexOf("<div",begindivtagindex)) > -1 ) {
		var beginsrcindex = html.indexOf("src=\"",begindivtagindex);
		if(beginsrcindex>-1) {
			beginsrcindex = beginsrcindex + 5;
			var endsrcindex = html.indexOf("\"",beginsrcindex);
			var scriptsrc = html.substring(beginsrcindex,endsrcindex);

			var beginidindex = html.indexOf("id=\"",begindivtagindex)+4;
			var endidindex = html.indexOf("\"",beginidindex);
			var id = html.substring(beginidindex,endidindex);
			if(scriptsrc.length > 0) {
				var domel = scope.getElementById(id);
				loadhtml(domel,scriptsrc,oncomplete);
			}
		}
		begindivtagindex = html.indexOf(">",begindivtagindex)+ 1;
	};
}
function addhtml(container,html,oncomplete) {
	addscopedhtml(document,container,html,oncomplete)
}

function loadhtml(frame, url,oncomplete) { 
	if(url==undefined) { alert('url for frame ' + frame.id + ' is undefined'); return }
	var pagename = url.match(/^\w*/);
	jQuery.ajax({ 
		url: url,
		async:false,
		success: function(result) { 
		var beginbodytagindex;
		var endbodytagindex;
		var bodyattributes;
		beginbodytagindex = result.indexOf("<body");
		endbodytagindex = result.indexOf(">",beginbodytagindex);
		bodyattributes = result.substring(beginbodytagindex + 5, endbodytagindex);
		beginbodytagindex = result.indexOf(">",beginbodytagindex) +1 ;
		endbodytagindex = result.indexOf("</body>");
		var bodytag = result.substring(beginbodytagindex,endbodytagindex);
		
		//add the html
		frame.innerHTML = '<span class="' + pagename + '"><span ' + bodyattributes + ' >' + bodytag + '</span></span>';
		
		//handle scripts
		var script;
		var beginscripttagindex=0;
		var scriptindex=0;
		var scriptsrcarray = new Array();
		var scriptarray = new Array();
		while((beginscripttagindex = bodytag.indexOf("<script",beginscripttagindex)) > -1 ) {
			var beginscripttagindex2 = bodytag.indexOf(">",beginscripttagindex)+ 1;
			var endscripttagindex = bodytag.indexOf("</script>",beginscripttagindex2);
			var scripttag = bodytag.substring(beginscripttagindex2,endscripttagindex).trim();
			if (scripttag.length == 0) {
				var beginsrcindex = bodytag.indexOf("src=\"",beginscripttagindex)+5;
				var endsrcindex = bodytag.indexOf("\"",beginsrcindex);
				var scriptsrc = bodytag.substring(beginsrcindex,endsrcindex);
				scriptsrcarray[scriptindex] = scriptsrc;
				scriptarray[scriptindex] = null;
			} else {
				//scope the lookup of dom elements
				//var scripttag = scripttag.replaceAll('document.',"innerdoc('" + frame.id + "').");
				while(scripttag.indexOf( 'document.' ) > -1) {
					scripttag = scripttag.replace('document.',"innerdoc('" + frame.id + "').");
				}
				while(scripttag.indexOf( 'addhtml(' ) > -1) {
					scripttag = scripttag.replace('addhtml(',"addscopedhtml(innerdoc('" + frame.id + "'),");
				}

				//alert(scripttag);
				//store the script
				scriptsrcarray[scriptindex] = scripttag;
				scriptarray[scriptindex] = scripttag;
			}
			beginscripttagindex = beginscripttagindex2;
			scriptindex++;
		};
		//the full amount of script sources is known, retrieve scripts
		for(var i=0;i<scriptsrcarray.length;i++) {
			if(scriptsrcarray[i].endsWith('.js') || scriptsrcarray[i].startsWith('http://')) {
				if(!isAuxiallaryScript(scriptsrcarray[i])) {
					getScript(frame,scriptsrcarray,scriptarray,i,oncomplete);
				} else {
					scriptarray[i] = 'alert("auxillary external script should not be evaluated")'
				}
			}
		}
		//try to execute the scripts
		executeScripts(frame,scriptsrcarray,scriptarray,oncomplete);			
 	}});
}
function isAuxiallaryScript(url) {
	for(var i=0;i<auxiallaryjs.length;i++) {
		if(auxiallaryjs[i]==url) return true;
	}
	return false;
}
function executeScripts(frame,urls,scripts,oncomplete) {
	//all scripts must be present
	for(var i=0;i<scripts.length;i++) {
		if(scripts[i] == null) { return; }
	}
	//execute url referenced scripts
	for(var i=0;i<scripts.length;i++) {
		if(urls[i].indexOf('/') > 0) {
			if(urls[i].endsWith('.js') || urls[i].startsWith('http://')) {
				if(!isAuxiallaryScript(urls[i])) {
					//alert(scripts[i]);
					eval(scripts[i]); 
				} //else { alert('ignore ' + urls[i])}
			}
		}
	}
	//collect inline scripts
	var script='';
	for(var i=0;i<scripts.length;i++) {
		//alert(urls[i]);
		//either script is external but local to the template library
		//either the script is internal
		if((urls[i].endsWith('.js') && urls[i].indexOf('/') == -1) ||  
		   (!urls[i].endsWith('.js') && !urls[i].startsWith('http://')) ) {
			//alert(script);
			script += '\n' + scripts[i];
		}
	}

	//pre- and postscript
	var prescript = 'this.frame=function() { return document.getElementById("' + frame.id  + '") };document.getElementById("' + frame.id  + '").template=this;var fthis = this; ';
	var postscript = '';
	//wrap in fie to scope the scripts
	script = 'tmp = new function() { \n ' + prescript + '\n' + script + '\n' + postscript + ' \n }()';
	//alert(script);
	//execute scoped script
	eval(script);
	if(oncomplete != undefined) oncomplete(frame);
}

function getScript(frame,urls,scripts, scriptindex,oncomplete) {
	scripts[scriptindex] = null;
	
	/*var headID = document.getElementsByTagName("head")[0];         
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	//newScript.onload=function() { executeScripts(urls,scripts) } ;
	newScript.src = urls[scriptindex];
	headID.appendChild(newScript);*/
	
	//console.log(urls[scriptindex]);
	jQuery.get(urls[scriptindex],{},function(result) { 
		scripts[scriptindex] = result;
		executeScripts(frame,urls,scripts,oncomplete);
	});
}

function iframedoc(iframe) {
	if (iframe.contentDocument) { 
		return iframe.contentDocument; 
	}
	else {
		return iframe.Document
	}
}
function htmltarget(parametername) {
	return eval("window._" + parametername + "target");
}


//default parameters = { float:'none', border:0, resizeHeight: true;=, resizeWidth: false, width: 100%, putIn: null, src: null, name:nil, resizableHeight:false, style:'' }
function createIFrame(itemname, parameters) {
	var withstyle="";
	var cssClass="";
	var srcTag="";
	var nameTag="";
	var floatstyle="";
	var borderstyle="";
	var style="";

	if(parameters != undefined) {
		if(parameters.border != undefined) {
			borderstyle="border:'" + parameters.border + "'"
		}	
		if(parameters.resizeWidth != true) {
			withstyle="width:100%;"
		}	
		if(parameters.width != undefined) {
			withstyle="width:" + parameters.width + ";"
		}	
		if(parameters.float != undefined && parameters.float !='none') {
			floatstyle="float:" + parameters.float + ";"
		}	
		if(parameters.cssClass != undefined) {
			cssClass="class='" + parameters.cssClass + "'";
		}	
		if(parameters.style != undefined) {
			style=parameters.style;
		}	
		if(parameters.src != undefined) {
			srcTag="src=\"" + parameters.src + "\"";
		}	
		if(parameters.name != undefined) {
			nameTag="name='" + parameters.name + "'";
		}
	}	
	//overflow:hidden;
	var htmlcode = '<div ' + nameTag + ' id="' + itemname +  '" ' + cssClass + ' scrolling="no"  style="' + floatstyle + borderstyle + withstyle + style + '"' + srcTag + ' ></div>';
	//alert(parameters);

	if(parameters != undefined) {
		if(parameters.resizeHeight != false) {
			iframeHeightToResize(itemname);
		}
		if(parameters.resizeWidth == true) {
			iframeWidthToResize(itemname);
		}
		if(parameters.putIn != undefined) {
			//alert(parameters.target);
			parameters.putIn.innerHTML = htmlcode;
			var frame = document.getElementById(itemname);
			frame.src= function(url) { 
				loadhtml(frame, url); 
				//alert('loaded ' + frame.id + ' ' + url); 
			};
		}
		if(parameters.resizableHeight == true) {
			//alert(parameters.resizableHeight);
			makeIFrameHeightResizable(document.getElementById(itemname));
		}
		if(parameters.src != undefined && parameters.putIn != undefined) {
			var frame = document.getElementById(itemname);
			frame.src(parameters.src);
		}
	}
	return htmlcode;
}

function iframeToResize() { }
function makeIFramesResizable() { }
function makeIFrameHeightResizable() { }
function iframeWidthToResize() {}
function iframeHeightToResize() {}


function innerdoc(parentId) {
	return { getElementById:function(anId) { 
		elementarray = document.getElementById(parentId).getElementsByTagName('*');  
		for(var i=0;i<elementarray.length;i++) {
			if(elementarray[i].id == anId) return elementarray[i]; 
		}
	} }
}

function addStyleSheet(url) {
	if(document.createStyleSheet) {
		document.createStyleSheet(url);
	}
	else {
		var styles = "@import url(' " + url + " ');";
		var newSS=document.createElement('link');
		newSS.rel='stylesheet';
		newSS.href='data:text/css,'+escape(styles);
		document.getElementsByTagName("head")[0].appendChild(newSS);
	}
}
function refreshparentframe() {
	
}
function setDisplayNone(obj) {
	obj.style.display='none';		
	refreshparentframe();
}
function setDisplayBlock(obj) {
	obj.style.display='block';
	refreshparentframe();
}
function toggleDisplay(obj) {
	if(obj.style.display=='none') {
		setDisplayBlock(obj);	
	}
	else {
		setDisplayNone(obj);
	}
}

if(document.uniqueNumber==undefined) document.uniqueNumber = 0;
function uniqueNumber() {
	document.uniqueNumber = document.uniqueNumber + 1;
	return document.uniqueNumber;
}

function openlink(ahref) {
	if(ahref.target=='undefined') {return true;}
	var el;
	var els = document.getElementsByName(ahref.target);
	if(els.length==0) {
		//might be due to a broken getElementsByName 
		els = getElementsByName_iefix('div',ahref.target)
		if(els.length==0) {
			//alert('no frame with name ' + ahref.target + ' found');
			return;
		}
	}
	el = els[0];
	
	loadhtml(el,ahref.href);
	return false;
}


function getElementsByName_iefix(tag, name) {
     
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}

function htmlelement(id) {
	return document.getElementById(id);
}
var rootdoc = document;

function concat(list,separator) {
	var str = '';
	if(list.length > 0) str = list[0];
	for(var i=1;i<list.length;i++){
		str += separator + list[i];
	}
	return str;
}

function frame(){
	return document.getElementsByTagName('body')[0];
}
