

var CIC = CIC || {};

CIC.util = {};

( function () {

	var loadingImage = [];
	var tabLoaded = []; 
	var buttonArray = [];
	var loadingDisplayMsg = "<p class='cicbody'>The tab is loading, please wait...</p>";
	var imagesInitialized = false;
	var loadingSomething = false;
    var dom = YAHOO.util.Dom;
    var event = YAHOO.util.Event;


	var loadingImage = [];
	loadingImage[0] = "/cic/images/ajax-loader.gif";
	loadingImage[1] = "/cic/images/spacer.gif";
	loadingImage[2] = "/cic/images/ajax-loader-err.gif";
	
	for (var i=0; i < loadingImage.length; i++) {
    	var preload = new Image();
    	preload.src = loadingImage[i];
	};

	YAHOO.util.Event.addListener(window, "scroll" , function() {
		  	CIC.util.updatePosition();
	});

	var isUndefined = YAHOO.lang.isUndefined;
	var isArray = YAHOO.lang.isArray;
	var defaultCardType = "O";
	


CIC.util = {
	
	doCheck : function(obj) {
		var elem = YAHOO.util.Dom.get(obj);
		
		if ( elem ) {
			elem.checked = true;
		}
	},
	
	isRadioChecked: function(radio) {
		if (radio) {
			if ( radio.length ) {
				for ( var i = 0; i < radio.length; i++ ) {
					if ( radio[i].checked ) 
						return true;
				}
			} else {
				if ( radio.checked ) return true;
			} 
		}		
		return false;
	},
	
	emptyElement : function(obj) {
		var elem = YAHOO.util.Dom.get(obj);
		
		if ( elem ) {
			elem.value = '';
		}
	}, 

	doCheckIfEmpty : function(obj,empty) {
		var elem = YAHOO.util.Dom.get(obj);
		var elemEmpty = YAHOO.util.Dom.get(empty);
		
		if ( elem && elemEmpty && YAHOO.lang.trim(elemEmpty.value).length === 0 ) {
			elem.checked = true;
		}
	},

	doSelectDropdownByValue : function(obj,value) {
		var elem = YAHOO.util.Dom.get(obj);
		
		if ( elem ) {
			elem.checked = true;
		}
	},

	fullJSONPrint : function(obj, id) {

	    function getSpaces(t) {
	        var i,
	            ret = '';
	        for (i = 0; i < (t * 3); ++i) {
	            ret += ' ';
	        }
	        return ret;
	    }
	 
	    function toStringFromJSON(obj, level) {
		        var i,
		            result = '';
		        for (i in obj) {
		            if (obj.hasOwnProperty(i)) {
		                if (YAHOO.lang.isObject(obj[i])) {
		                    result += getSpaces(level) + i + ': <br>' +
		                        toStringFromJSON(obj[i], level + 1) + '<br>';
		                } else {
		                    result += getSpaces(level) + i + ' : ' + obj[i] + '<br>';
		                }
		            }
		        }
		        return result;
		}
		
		var element = document.getElementById(id);
		if (element) {
		    element.innerHTML = '<pre>' + toStringFromJSON(obj, 0) + '</pre>';
		}
	},
	
 	loadingError : function() {
		document.getElementById("loading_image").src=loadingImage[2];
	},
	
	loadingDisplay : function(v) {
   		document.getElementById( v ).innerHTML = loadingDisplayMsg;
	},
	
	getPageScroll : function() {

		var yScroll;
	
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
		}
	
		arrayPageScroll = new Array('',yScroll) 
		return arrayPageScroll;
	},
	
	getPageSize : function() {
		var xScroll, yScroll;
		var windowWidth, windowHeight;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
	
	
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	},
	
	loadingApplication : function(yes) {
	  if ( !imagesInitialized ) {
			var arrayPageSize = this.getPageSize();
			var arrayPageScroll = this.getPageScroll();
			document.getElementById("loading_image").style.position = 'absolute';
			document.getElementById("loading_image").style.zIndex = '150';
			document.getElementById("loading_image").style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - 66) / 3) + 'px');
			document.getElementById("loading_image").style.left = (((arrayPageSize[0] - 20 - 66) / 2) + 'px');
			document.getElementById("loading_image").style.display = 'block';
			imagesInitialized=true;
	  }
	  
	  if ( yes ) {
	//  	if ( loadingSomething ) {
	 // 		alert("A load is taking place. Try your click once the load is done.");
	  //		return true;
	  //	}
		var arrayPageSize = this.getPageSize();
		var arrayPageScroll = this.getPageScroll();
		dom.get("loading_image").style.top = (arrayPageScroll[1]+110) + 'px';
		dom.get("loading_image").style.left = '500px';
//		document.getElementById("loading_image").style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - 66) / 3) + 'px');
		//document.getElementById("allbody").style.backgroundColor="#FFCC80";
		//document.getElementById("allbody").style.backgroundRepeat = "no-repeat";
		//document.getElementById("allbody").style.backgroundImage = "url('/cic/images/ajax-loader.gif')";
		document.getElementById("loading_image").src=loadingImage[0];
	  } else { 
		//document.getElementById("allbody").style.backgroundImage = "url('/cic/images/spacer.gif')";
		document.getElementById("loading_image").src=loadingImage[1];
	  }
	  loadingSomething = yes;
	  return false;
	},

	updatePosition : function() {
		  if ( loadingSomething ) {
			var arrayPageSize = this.getPageSize();
			var arrayPageScroll = this.getPageScroll();
			dom.get("loading_image").style.top = (arrayPageScroll[1]+110) + 'px';
			dom.get("loading_image").style.left = '500px';
		  }
	},
	
	/**
	 * Converts data to an array if it is atomic
	 * @method arrayify
	 * @param {*|Array} data The data to be possibly converted into an array
	 * @namespace FTW.util
	 * @static
	 */
	
	arrayify : function(data) {
	//alert("isArray " +  isArray(data));
	    return isUndefined(data) ? [] : (isArray(data) ? data : [data]);
	},
	
	setFieldWarnings: function(arr,ext) {
		for ( var i = 0; i < arr.length; i++ ) {
			var elName = arr[i] + "-" + ext + "err";
			if ( dom.get(elName) ) {
				dom.addClass(dom.get(elName),"warningFieldset");
			}
		}
	},
	
	clearFieldWarnings: function(arr,ext) {
		for ( var i = 0; i < arr.length; i++ ) {
			var elName = arr[i] + "-" + ext + "err";
			if ( dom.get(elName) ) {
				dom.removeClass(dom.get(elName),"warningFieldset");
			}
		}
	},
	
 	handleSuccess:function(o){
 	},
 	
	setInitialDefaultCardType : function(card) {
		defaultCardType = card;
	},

	setDefaultCardType : function(card,doNotLoad) {
		defaultCardType = card;
		if (!doNotLoad) {
			this.loadingApplication(true);
			YAHOO.util.Connect.asyncRequest('GET', "/cic/PR?app=9999&action=11&cardType=" + card, {
										success:this.handleSuccess,
										failure:this.handleSuccess,
									  	cache:false,
										scope: this });
			setTimeout(this.refreshViews,1500);
		}
	},

	getDefaultCardType : function() {
		return defaultCardType;
	},
	
	refreshViews:function(){
			var tmpIndx = tabView.get('activeIndex');
			var tmpIndexR = tmpIndx + 1;
			CIC.TAB4.resetTab(false);
			CIC.TAB5.resetTab(false);
			CIC.TAB6.resetTab(false);
			CIC.TAB7.resetTab(false);
			//alert("Resetting Tab " + tmpIndexR); 
			CIC['TAB'+tmpIndexR].resetTab(true);
			//tabView.deselectTab(tmpIndx);
			//tabView.selectTab(tmpIndx);
	},
	
	toggleCal: function(cal) {
       if (document.getElementById(cal.containerId).style.display === 'none') {
            cal.show();
            document.getElementById(cal.showLink).style.display = 'none';
            document.getElementById(cal.hideLink).style.display = 'inline';
        } else {
            cal.hide();
            document.getElementById(cal.hideLink).style.display = 'none';
            document.getElementById(cal.showLink).style.display = 'inline';
        }
	},

	getDateString: function(date) {
	    return (date.getMonth() + 1) + '/' + date.getDate() + '/' +
            date.getFullYear();
	},

	getCalDate: function(cal, args) {
       CIC.util.toggleCal(cal);
       return cal.toDate(args[0][0]);
	},

	makeCallback: function(data) {
	    var callback = {
            cache: false,
            timeout: 0
            //timeout: 30000
        };
	    return YAHOO.lang.merge(callback, data || {});
	},

	handleOverlaySuccess: function(o) {
        var html = null;
        var msg = null;
        var msgIdx = o.responseText.indexOf("--MESSAGE--", 0);

        html = o.responseText;
        if (msgIdx >= 0) {
            html = o.responseText.substring(0, msgIdx);
            msg = o.responseText.substring(msgIdx + 11);
        }

        if (msg != null) {
            CIC.util.loadingApplication(false);
            alert(msg);
            return;
        }
        this.showOverlay(html, o.argument[0], o.argument[1]);
        this.loadingApplication(false);
	},
	modal: document.getElementById('modal'),
	showModal: function() {
	    var docEl = document.documentElement,
	        s = this.modal.style;
	    s.height = docEl.scrollHeight + 'px';
	    s.width = docEl.scrollWidth + 'px';
	    s.display = 'block';
	},
	hideModal: function() {
	    this.modal.style.display = 'none';
	},
	overlay: document.getElementById('overlay'),
	showOverlay: function(html, width, height) {
        var Dom = YAHOO.util.Dom,
            el = Dom.get("overlaybody"),
            minOffset = 10,
            elementWidth = width || el.offsetWidth,
            elementHeight = height || el.offsetHeight,
            s = this.overlay.style,
            viewPortWidth = Dom.getViewportWidth(),
            viewPortHeight = Dom.getViewportHeight(),
            x,
            y;

        // center it
        if (elementWidth < viewPortWidth) {
            x = (viewPortWidth / 2) - (elementWidth / 2) +
                Dom.getDocumentScrollLeft();
        } else {
            x = minOffset + Dom.getDocumentScrollLeft();
        }
    
        if (elementHeight < viewPortHeight) {
            y = (viewPortHeight / 2) - (elementHeight / 2) +
                Dom.getDocumentScrollTop();
        } else {
            y = minOffset + Dom.getDocumentScrollTop();
        }

        this.showModal();
        el.innerHTML = html;
        s.display = 'block';
        s.width = elementWidth + 'px';
        s.height = elementHeight + 'px';
        Dom.setXY(this.overlay, [x, y]);
        document.body.style.overflow = 'hidden';
	    // force redraw
//	    s.borderTop = '1px solid black';
//	    setTimeout(function() {
//	        s.borderTop = 'none';
//	    }, 0);
	},
	hideOverlay: function() {
	    this.overlay.style.display = 'none';
	    document.body.style.overflow = 'auto';
	    this.hideModal();
	    return false;
	}
};

})();

CIC.util.initClickButton = function(name,func,scope) {
	if ( YAHOO.util.Dom.get( name ) != null ) {		  
		var oSubmitButton2 = new YAHOO.widget.Button(name);  
    	oSubmitButton2.addListener("click", func,scope,true);
    }   

};

YAHOO.util.Connect.createFrame = function(secureUri){

	var ie = YAHOO.env.ua.ie;
    // IE does not allow the setting of id and name attributes as object
    // properties via createElement().  A different iframe creation
    // pattern is required for IE.
    var frameId = 'yuiIO' + this._transaction_id,
                    io;
    if(ie && ie < 9 ){
                    io = document.createElement('<iframe id=\"' + frameId + '\" name=\"' + frameId + '\" />');

                    // IE will throw a security exception in an SSL environment if the
                    // iframe source is undefined.
                    if(typeof secureUri == 'boolean'){
                                    io.src = 'javascript:false';
                    }
    }
    else{
                    io = document.createElement('iframe');
                    io.id = frameId;
                    io.name = frameId;
    }

    io.style.position = 'absolute';
    io.style.top = '-1000px';
    io.style.left = '-1000px';

    document.body.appendChild(io);
   // alert('File upload iframe created. Id is:' + frameId, 'info', 'Connection');
};



YAHOO.util.Connect.uploadFile = function(o, callback, uri, postData){
	// Each iframe has an id prefix of "yuiIO" followed
	// by the unique transaction id.
	var frameId = 'yuiIO' + o.tId,
	    uploadEncoding = 'multipart/form-data',
	    io = document.getElementById(frameId),
	    ie8 = (document.documentMode && document.documentMode === 8) ? true : false,
	    oConn = this,
		args = (callback && callback.argument)?callback.argument:null,
        oElements,i,prop,obj, rawFormAttributes, uploadCallback;

	
	// Track original HTML form attribute values.
	rawFormAttributes = {
		action:this._formNode.getAttribute('action'),
		method:this._formNode.getAttribute('method'),
		target:this._formNode.getAttribute('target')
	};

	// Initialize the HTML form properties in case they are
	// not defined in the HTML form.
	this._formNode.setAttribute('action', uri);
	this._formNode.setAttribute('method', 'POST');
	this._formNode.setAttribute('target', frameId);
	if(YAHOO.env.ua.ie != 8 ){
		// IE does not respect property enctype for HTML forms.
		// Instead it uses the property - "encoding".
		this._formNode.setAttribute('encoding', uploadEncoding);
	}
	else{
		this._formNode.setAttribute('enctype', uploadEncoding);
	}

	if(postData){
		oElements = this.appendPostData(postData);
	}

	//alert("submitting form " + this._formNode.getAttribute("name"));
	// Start file upload.
	this._formNode.submit();

	// Fire global custom event -- startEvent
	this.startEvent.fire(o, args);

	if(o.startEvent){
		// Fire transaction custom event -- startEvent
		o.startEvent.fire(o, args);
	}

	// Start polling if a callback is present and the timeout
	// property has been defined.
	if(callback && callback.timeout){
		this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
	}

	// Remove HTML elements created by appendPostData
	if(oElements && oElements.length > 0){
		for(i=0; i < oElements.length; i++){
			this._formNode.removeChild(oElements[i]);
		}
	}

	// Restore HTML form attributes to their original
	// values prior to file upload.
	for(prop in rawFormAttributes){
		if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
			if(rawFormAttributes[prop]){
				this._formNode.setAttribute(prop, rawFormAttributes[prop]);
			}
			else{
				this._formNode.removeAttribute(prop);
			}
		}
	}

	// Reset HTML form state properties.
	this.resetFormState();

	// Create the upload callback handler that fires when the iframe
	// receives the load event.  Subsequently, the event handler is detached
	// and the iframe removed from the document.
	uploadCallback = function() {
		if(callback && callback.timeout){
			window.clearTimeout(oConn._timeOut[o.tId]);
			delete oConn._timeOut[o.tId];
		}

		// Fire global custom event -- completeEvent
		oConn.completeEvent.fire(o, args);

		if(o.completeEvent){
			// Fire transaction custom event -- completeEvent
			o.completeEvent.fire(o, args);
		}

		obj = {
		    tId : o.tId,
		    argument : callback.argument
        };

		try
		{
			// responseText and responseXML will be populated with the same data from the iframe.
			// Since the HTTP headers cannot be read from the iframe
			obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
			obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
		}
		catch(e){}

		if(callback && callback.upload){
			if(!callback.scope){
				callback.upload(obj);
				YAHOO.log('Upload callback.', 'info', 'Connection');
			}
			else{
				callback.upload.apply(callback.scope, [obj]);
				YAHOO.log('Upload callback with scope.', 'info', 'Connection');
			}
		}

		// Fire global custom event -- uploadEvent
		oConn.uploadEvent.fire(obj);

		if(o.uploadEvent){
			// Fire transaction custom event -- uploadEvent
			o.uploadEvent.fire(obj);
		}

		YAHOO.util.Event.removeListener(io, "load", uploadCallback);

		setTimeout(
			function(){
				document.body.removeChild(io);
				oConn.releaseObject(o);
				YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
			}, 100);
	};


	// Bind the onload handler to the iframe to detect the file upload response.
	YAHOO.util.Event.addListener(io, "load", uploadCallback);
};

