/*
$Date: 2011-05-27 17:11:58 +0200 (vr, 27 mei 2011) $
$Revision: 5753 $
*/

/**
 * windowsType enumeration
 */
var ePCWindowType = { PopUp:0, PopIn:1, NewWindow:2 };
var ePCCallType = { Unknown:0, WebToPhone:1, CallMeNow:2, CallMeLater:3 };
var ePCEventName = { UNKNOWN:0, INITIALIZING:1, INITIALIZED:2, READY_TO_CALL:3, CREATING_CALL:4, CALL_CREATED:5, CALL_FAILED:6, CALL_QUEUED:7, OC_STARTING_AUDIO_TEST:8, OC_AUDIO_TEST_SUCCESS:9, OC_AUDIO_TEST_FAILED:10, UNKNOWN_TARGET:11, CLOSED:12, NOT_AVAILABLE:13, ERROR: 14 };
var ePCAudioTestStep = { UNKNOWN:0, SPEAKER_TEST:1, MIC_DETECTION:2, MIC_TEST:3 };

var pcscom_protocol = (document.location.protocol=="https:")? "https:" : "http:";
var pcscom_menuElementId = 'pcscom_pop';

if(typeof document.compatMode!='undefined'&&document.compatMode!='BackCompat'){
	pc_t1_DOCtp="_top:expression(document.documentElement.scrollTop+document.documentElement.clientHeight-this.clientHeight);_left:expression(document.documentElement.scrollLeft + document.documentElement.clientWidth - offsetWidth);}";
	pc_t1_DOCtp2="_top:expression(document.documentElement.scrollTop-20+document.documentElement.clientHeight-this.clientHeight);}";
}else{
	pc_t1_DOCtp="_top:expression(document.body.scrollTop+document.body.clientHeight-this.clientHeight);_left:expression(document.body.scrollLeft + document.body.clientWidth - offsetWidth);}";
	pc_t1_DOCtp2="_top:expression(document.body.scrollTop+(ignoreme=(document.body.clientHeight/2)));}";
}

var pcscom_fixedCSS='#pcscom_fixed{position:fixed;';
pcscom_fixedCSS+= '_position:absolute;';
pcscom_fixedCSS+= 'bottom:0px;';
pcscom_fixedCSS+= 'right:0px;';
pcscom_fixedCSS+= 'clip:rect(0 100 100 0);';
pcscom_fixedCSS+= 'z-index: 10000;';
pcscom_fixedCSS+= pc_t1_DOCtp;

var pcscom_popCSS = '#pcscom_pop {background-color: transparent;';
pcscom_popCSS+= 'position:fixed;';
pcscom_popCSS+= '_position:absolute;';
pcscom_popCSS+= 'width: 600px;';
pcscom_popCSS+= 'height: 300px;';
pcscom_popCSS+= 'top: 50%;';
pcscom_popCSS+= 'left: 50%;';
pcscom_popCSS+= 'margin-left: -300px;';
pcscom_popCSS+= 'margin-top: -150px;';
pcscom_popCSS+= 'overflow: hidden;';
pcscom_popCSS+= 'visibility: hidden;';
pcscom_popCSS+= 'z-index: 10000;';
pcscom_popCSS+= pc_t1_DOCtp2;

document.write('<style type="text/css">'+pcscom_fixedCSS+pcscom_popCSS+'</style>');



/**
 * Helper function to hide or show an HTML block element
 * @param elementId A string containing the id of the element
 * @param show A boolean specifying wether the element should be made visible or hidden
 */
function pcscom_showElement( elementId, show ){
	if(document.getElementById){
		eval("document.getElementById(elementId).style.visibility=\""+((show)? 'visible':'hidden')+"\"");
	}else{	
		if(document.layers){
			document.layers[elementId].visibility=(show)? 'show':'hidden';
		}else{
			if(document.all){
				eval("document.all."+elementId+".style.visibility=\""+((show)? 'visible':'hidden')+"\"");
			}
		}
	}
}

/**
 * Helper function to add a function to the queue to be executed when the page finishes loading
 * @param func A reference to a function that needs to be executes when the pages finishes loading
 */
function pcscom_addLoadEvent( func ){
	if(typeof window.addEventListener != 'undefined') 
		window.addEventListener('load', func, false);//.. gecko, safari, konqueror and standard
	else if(typeof document.addEventListener != 'undefined') document.addEventListener('load', func, false); //.. opera 7
	else if(typeof window.attachEvent != 'undefined') window.attachEvent('onload', func); //.. win/ie
}

/**
 * Helper function to get an element in the html document. This is more-or-less browser independant
 * @param elementId A string with the id of the element
 */
function pcscom_getElement( elementId ){
	if(document.getElementById) return document.getElementById(elementId);
		else if(document.layers) return document.layers[elementId];
			else if(document.all) return eval("document.all."+elementId);
}

/**
 * Helper function to generate the html element which embeds a Flash movie. This code does some browser detection
 * @param movieUrl A string containing URL of the Flash movie (.swf)
 * @param elementId A string containing the id of the element. This can be used for future references to the flash movie
 * @param width An integer value specifying the width of the movie
 * @param height An integer value specifying the height of the movie
 * @param flashVars A string containing the variables which should be passed on to the flash movie (form: "param1name=param1value&param2name=param2value")
 */
function pcscom_getFlashElement( movieUrl, elementId, width, height, flashVars, transparent ){
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	
	if (isIE){
		var flashElement = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
		flashElement+= 'codebase="'+pcscom_protocol+'//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"';
		flashElement+= 'width="' + width + '" ';
		flashElement+= 'height="' + height + '" ';
		flashElement+= 'id="' + elementId + '" ';
		flashElement+= 'align="" ';
		flashElement+= 'onClick="var e=e||event;e.stopPropagation? e.stopPropagation() : e.cancelBubble=true;" ';
		flashElement+= '>';
		flashElement+= '<param name="movie" value="' + movieUrl + '"></param>';
		flashElement+= '<param name="quality" value="high" />';
		flashElement+= (transparent)? '<param name="wmode" value="transparent" />' : '';
		flashElement+= '<param name="flashvars" value="' + flashVars + '" />';
		flashElement+= '<param name="allowscriptaccess" value="always" />';
		flashElement+= '</object>';
	}else{
		var flashElement = '<embed " ';
		flashElement+= 'type="application/x-shockwave-flash" ';
		flashElement+= 'src="' + movieUrl + '" ';
		flashElement+= 'width="' + width + '" ';
		flashElement+= 'height="' + height + '" ';
		flashElement+= 'id="' + elementId + '" ';
		flashElement+= 'name="' + elementId + '" ';
		flashElement+= 'align="" ';
		flashElement+= 'flashvars="' + flashVars + '" ';
		flashElement+= (transparent)? 'wmode="transparent" ' : '';
		flashElement+= 'quality="high" ';
		flashElement+= 'allowscriptaccess="always" ';
		flashElement+= 'onClick="var e=e||event;e.stopPropagation? e.stopPropagation() : e.cancelBubble=true;" ';
		flashElement+= '>';
		flashElement+= '</embed>';
	}
	return flashElement;
}

/**
 * Helper function to open a popup width the specified URL
 * @param url A string containing URL of the page to display in the popup
 * @param width An integer value specifying the width of the popup window
 * @param height An integer value specifying the height of the popup window
 */
function pcscom_openPopup( url, width, height ){
	try{
		if( width!==undefined && height!==undefined ){
			newWindow=open(url,'new_window','WIDTH='+width+',HEIGHT='+height+',FRAMEBORDER=0,MARGINWIDTH=0,MARGINHEIGHT=0,SCROLLBARS=0,allowtransparency=true');
		}else{
			newWindow=open(url,'_blank');
		}
	}catch(e){
		alert( "Could not open a new window for the selected contact tool. Please disable your popup blocker.");
	}
	if ( newWindow==null || typeof(newWindow)=="undefined" || (window.opera && !newWindow.opera) ){
		alert( "Could not open a new window for the selected contact tool. Please disable your popup blocker.");
	}else{
		if(window.focus) newWindow.focus();
		return newWindow;
	}
	return false;
}

/**
* Class definition of the Smart Contact Button
*/
function PCSCOM( target, options ){
	this._target = target;

	this._showOnNA = ( (options !== undefined) && (typeof options.showOnNA == 'boolean') )? options.showOnNA : false;
	this._showOnClosed = ( (options !== undefined) && (typeof options.showOnClosed == 'boolean') )? options.showOnClosed : true;
	this._switchboardAddress = ( (options !== undefined) && (typeof options.switchboardAddress == 'string') )? options.switchboardAddress : "switchboard.pushcall.com";
	this._baseColor =  ( (options !== undefined) && (typeof options.baseColor == 'string') )? options.baseColor : '0xFD6700'; //Orange
	this._passReferrer =  ( (options !== undefined) && (typeof options.passReferrer == 'boolean') )? options.passReferrer : false;
    this._transparent =  ( (options !== undefined) && (typeof options.transparent == 'boolean') )? options.transparent : true;
	this._squareCorner =  ( (options !== undefined) && (typeof options.squareCorner == 'boolean') )? options.squareCorner : false;
	this._locale = ((navigator.browserLanguage) ? navigator.browserLanguage : (navigator.language) ? navigator.language : navigator.userLanguage);
	this._locale = ( (options !== undefined) && (typeof options.locale == 'string') )? options.locale : this._locale;
	
	this._mailUrl =  '';
	this._mailWindowType =  ePCWindowType.PopUp;
		
	this._menuVisible = false;
	
	this._cornerButtonMovieLocation = ( (options !== undefined) && (typeof options.cornerButtonMovieLocation == 'string') )? options.cornerButtonMovieLocation : pcscom_protocol+"//d5uouwl5c9tey.cloudfront.net/clients/smartcontact/corner_button.swf";
	this._overlayMovieLocation = ( (options !== undefined) && (typeof options.overlayMovieLocation == 'string') )? options.overlayMovieLocation : pcscom_protocol+"//d5uouwl5c9tey.cloudfront.net/clients/smartcontact/overlay.swf";
	
	this._ocWidth = 400;
	this._ocHeight = 300;
	this._cmnWidth = 400;
	this._cmnHeight = 300;
	this._chatWidth = 700;
	this._chatHeight = 700;
	this._mailWidth = 600;
	this._mailHeight = 600;
	
	//generate random name which will be used as objectId
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	this._objectId = "pcscom_";
	for (var i=0; i<8; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		this._objectId += chars.substring(rnum,rnum+1);
	}
	
	//globally register the name of the objectId as a variable for the callback requests from the flash movie
	eval(this._objectId+' = this;');
}

/**
* Callback function from Flash, indicating the end of hiding the menu
*/
PCSCOM.prototype.finishedHiding = function( ){
	pcscom_showElement( pcscom_menuElementId, false );
	this._menuVisible = false;
}

/**
* Callback function from Flash, indicating that the user selected one of the services
* @param serviceType A string value containing the service type that is selected
*/
PCSCOM.prototype.openService = function( serviceType ){
	//hide the menu
	this.showOverlayMenu( false );
	
	if( navigator.appName.indexOf("Opera") != -1 ){
		setTimeout( this._objectId+'.openServicePopup(\'' + serviceType +'\')', 100 );
	}else{
		this.openServicePopup(serviceType);
	}
}

/**
* Function that opens the popup for the selected service and takes care of showing the required HTML
* @param serviceType A string value containing the service type that is selected
*/
PCSCOM.prototype.openServicePopup = function( serviceType ){
	var newWindow = null;
	var resizable = false;
	switch( serviceType ){
		case 'cmn':
			buttonMovieLocation = "http://d5uouwl5c9tey.cloudfront.net/clients/audio/AudioClient.swf";
			flashVars = 'target='+this._target+'&switchboardAddress='+this._switchboardAddress+'&clientType=OfflineCalling&skinFile=http://d5uouwl5c9tey.cloudfront.net/skins/skin_'+this._target+'.swf&localeID='+this._locale+'&jsObject=opener.'+this._objectId+'&debug=true&nick=&domain=';
			newWindow = pcscom_openPopup( 'about:blank', this._cmnWidth, this._cmnHeight );
			width = 350;
			height = 250;
			break;
		case 'oc':
			buttonMovieLocation = "http://d5uouwl5c9tey.cloudfront.net/clients/audio/AudioClient.swf";
			flashVars = 'target='+this._target+'&switchboardAddress='+this._switchboardAddress+'&clientType=OnlineCalling&skinFile=http://d5uouwl5c9tey.cloudfront.net/skins/skin_'+this._target+'.swf&localeID='+this._locale+'&jsObject=opener.'+this._objectId+'&debug=true&nick=&domain=';
			newWindow = pcscom_openPopup( 'about:blank', this._ocWidth, this._ocHeight );
			width = 350;
			height = 250;
			break;
		case 'chat':
			buttonMovieLocation = "http://" + this._switchboardAddress + "/chat/client-chat-button.swf";
			flashVars = 'target='+this._target+'&switchboardAddress='+this._switchboardAddress+'&loadbalancerURL=http%3A%2F%2F'+this._switchboardAddress+'%2Fserver-loadbalancer&showCloseButton=false&localeID='+this._locale+'&pollDelay=3001&styleSheet=http://' + this._switchboardAddress + '/skins/css_'+this._target+'.swf';
			resizable = true;
			newWindow = pcscom_openPopup( 'about:blank', this._chatWidth, this._chatHeight );
			break;
		case 'mail':
			buttonMovieLocation = "http://" + this._switchboardAddress + "/mail/client-mail.swf";
			flashVars = 'target='+this._target+'&endpoint=http://'+this._switchboardAddress+'/server-mail/messagebroker/amf&servletPath=http://'+this._switchboardAddress+'/server-mail&localeID='+this._locale+'&showCloseButton=false&styleSheet=http://' + this._switchboardAddress + '/skins/css_'+this._target+'.swf';
			resizable = true;

			switch( this._mailWindowType ){
				case ePCWindowType.PopUp:
					newWindow = pcscom_openPopup( ((this._mailUrl == '')? 'about:blank' : this._mailUrl), this._mailWidth, this._mailHeight );
					if(this._mailUrl != '') newWindow = null;
					break;
				case ePCWindowType.PopIn:
					if(this._mailUrl != ''){
						window.location.href = this._mailUrl;
					}else{
						newWindow = window;
					}
					break;
				case ePCWindowType.NewWindow:
					newWindow = pcscom_openPopup( this._mailUrl );
					if(this._mailUrl != '') newWindow = null;
					break;
			}				
			break;			
	}

	if (newWindow){
			newWindow.document.open('text/html','replace');
			newWindow.document.write('<html>');
			newWindow.document.write('<head>');
			newWindow.document.write('<title>PushCall</title>');
            newWindow.document.writeln('<script language="JavaScript">');
            newWindow.document.writeln('	var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;');
            newWindow.document.writeln('	function setClientSize(w, h) {');
            newWindow.document.writeln('		var flashObject = isInternetExplorer ? document.all.flash : document.flash;');
            newWindow.document.writeln('		flashObject.width = w');
            newWindow.document.writeln('		flashObject.height = h');
            newWindow.document.writeln('}');
            newWindow.document.writeln('</script>');
			newWindow.document.write('</head>');
			newWindow.document.write('<body style="margin:0;height:100%;">');
			if (!resizable) newWindow.document.write('<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0"><tr><td><div align="center">');
			newWindow.document.write( pcscom_getFlashElement( buttonMovieLocation, 'flash', ((resizable)? '100%': width), ((resizable)? '100%': height), flashVars, true ) );
			if (!resizable) newWindow.document.write('</div></td></tr></table>');
			newWindow.document.write('</body>');
			newWindow.document.write('</html>');
			newWindow.document.close();
			newWindow.opener = self;
	}
}


/**
 * Shows or hides the Smart Contact menu
 * @param show A boolean that defines wether the menu should be shown or hidden
*/
PCSCOM.prototype.showOverlayMenu = function ( show ){
	var overlayMenuID = this._objectId + '_overlay';
	//alert('show: '+ show);
	if ( !pcscom_getElement(pcscom_menuElementId) ){
		var overlayMenu = document.createElement('div');
		overlayMenu.setAttribute( 'id', pcscom_menuElementId );
		document.body.appendChild( overlayMenu );
	}
	
	if ( show ){

		var flashVars = 'objectId='+this._objectId;
		flashVars += '&baseColor='+this._baseColor;
		flashVars += '&switchboardAddress='+this._switchboardAddress;
		flashVars += '&target='+this._target;
		flashVars += '&showOnNA='+((this._showOnNA)?"true":"false");
		flashVars += '&showOnClosed='+((this._showOnClosed)?'true':'false');
		flashVars += '&corner='+((this._squareCorner)?'true':'false');
		flashVars += '&localeID='+this._locale;
		
		el = pcscom_getElement(pcscom_menuElementId);
		el.innerHTML = pcscom_getFlashElement( this._overlayMovieLocation, overlayMenuID, 600, 300, flashVars, this._transparent );	
	
		//return from function when menu is already visible
		if( this._menuVisible ) return;
		
		//show DIV element
		pcscom_showElement( pcscom_menuElementId, true );

		//start show animation
		try{
			if( !(pcscom_getElement(overlayMenuID).IsPlaying()) )
				pcscom_getElement(overlayMenuID).startShowAnimation();
		}catch(e){
			//alert("Exception in startShowAnimation\nName: " + e.name + "\nError message: " + e.message + "\nflashMovie: " + pcscom_getElement(overlayMenuID) + "\nisPlaying: " + pcscom_getElement(overlayMenuID).IsPlaying() );
		}

	}else{
		pcscom_getElement(overlayMenuID).blur(); //this line is required for Internet Explorer (7)
		//start hide animation
		try{
			pcscom_getElement(overlayMenuID).startHideAnimation();
		}catch(e){
			//alert("Exception in startHideAnimation\nName: " + e.name + "\nError message: " + e.message + "\nflashMovie: " + pcscom_getElement(overlayMenuID) + "\nisPlaying: " + pcscom_getElement(overlayMenuID).IsPlaying());
		}
	}
	this._menuVisible = show;
}

/**
 * Toggles visibility of the Smart Contact menu
 */
PCSCOM.prototype.toggleMenu = function (){
	this.showOverlayMenu(!this._menuVisible);
}

/**
 * Creates a corner button 
 * @param options  An array containing optional parameters for creating the corner button
    baseColor: A string containing a RGB value to use as base color for the buttons. Format: 0xRRGGBB (hexidecimal). Default is "PushCall" orange
    captionText: (optional)  A string containing the text to show on the corner button. By default it is read from the database
 */
PCSCOM.prototype.createCornerButton = function( options ){
	var captionText = "Contact Us";
	var baseColor = this._baseColor;
	var showMailIcon = true;
	var showCallMeNowIcon = true;
	var showOnlineCallingIcon = true;
	var showChatIcon = true;
    var transparent = true;
	var parent = null;
	
	if( options !== undefined ){
		if( typeof options.baseColor == 'string' ) baseColor = options.baseColor;
		if( typeof options.captionText == 'string' ) captionText = options.captionText;
		if( typeof options.showMailIcon == 'boolean' ) showMailIcon = options.showMailIcon;
		if( typeof options.showCallMeNowIcon == 'boolean' ) showCallMeNowIcon = options.showCallMeNowIcon;
		if( typeof options.showOnlineCallingIcon == 'boolean' ) showOnlineCallingIcon = options.showOnlineCallingIcon;
		if( typeof options.showChatIcon == 'boolean' ) showChatIcon = options.showChatIcon;
        if( typeof options.transparent == 'boolean' ) transparent = options.transparent;
		if( typeof options.parent == 'string' ) parent = options.parent;
	}
	
	//create the DIV element for the corner button
	var cornerElement = null;
	if (parent){
		cornerElement = pcscom_getElement( parent );
	}
	if (!cornerElement){
		document.write("<div id=\"pcscom_fixed\"></div>");
		cornerElement = pcscom_getElement( 'pcscom_fixed' );
	}
	
	//Put the flash movie in the DIV
	var flashVars = 'objectId='+this._objectId+'&baseColor='+baseColor;
	flashVars+='&captionText='+captionText;
	flashVars+='&audio=' + ((showOnlineCallingIcon)? "true":"false");
	flashVars+='&cmn=' + ((showCallMeNowIcon)? "true":"false");
	flashVars+='&chat=' + ((showChatIcon)? "true":"false");
	flashVars+='&mail=' + ((showMailIcon)? "true":"false");
	
	cornerElement.innerHTML = pcscom_getFlashElement( this._cornerButtonMovieLocation, "cornerButton", 90, 80, flashVars, transparent );
}

/**
 * Sets the base color of the icoms in the Smart Overlay Menu
 * @param A string containing a RGB value to use as base color for the buttons. Format: 0xRRGGBB (hexidecimal)
 */
PCSCOM.prototype.setBaseColor = function( baseColor ){
	if(baseColor!==undefined) this._baseColor = baseColor;
}

PCSCOM.prototype.setEventListener = function( eventHandler ){
	if (eventHandler === undefined || typeof eventHandler != 'function' ) throw ('no (valid) eventHandler specified in call to setEventListener');
	this._eventHandler = eventHandler;
}	

PCSCOM.prototype.audioClientEventHandler = function( event, data ){
	var eEvent = ePCEventName.UNKNOWN;
	var eventData = eval('(' + data + ')');
	
	if (eventData.callType !== undefined){
		switch ( eventData.callType ){
			case 'OC': eventData.callType = ePCCallType.WebToPhone; break;
			case 'CMN': eventData.callType = ePCCallType.CallMeNow; break;
			case 'CML': eventData.callType = ePCCallType.CallMeLater; break;
			default: eventData.callType = ePCCallType.Unknown; break;
		}
	}
	
	if (eventData.audioTestStep !== undefined){
		eventData.audioTestStep = ( ePCAudioTestStep[eventData.audioTestStep] )? ePCAudioTestStep[eventData.audioTestStep] : ePCAudioTestStep.UNKNOWN;
	}
	
	if (eventData.date !== undefined){
		eventData.date = new Date( eventData.date );
	}
	
	if ( ePCEventName[event] ) eEvent = ePCEventName[event];
	  else alert( event );
	  
	if ( eEvent != ePCEventName.UNKNOWN && this._eventHandler !== undefined && typeof this._eventHandler == 'function' ){
		this._eventHandler( eEvent, eventData);
	}
	
	
}

/**
 * Sets the size of the popup window for the Online Calling client
 * @param width The width of the popup in pixels
 * @param height The height of the popup in pixels
 */
PCSCOM.prototype.setOnlineCallingSize = function( width, height ){
	this._ocWidth = width;
	this._ocHeight = height;
}

/**
 * Sets the size of the popup window for the Call-Me-Now client
 * @param width The width of the popup in pixels
 * @param height The height of the popup in pixels
 */
PCSCOM.prototype.setCallMeNowSize = function( width, height ){
	this._cmnWidth = width;
	this._cmnHeight = height;
}

/**
 * Sets the size of the popup window for the Chat client
 * @param width The width of the popup in pixels
 * @param height The height of the popup in pixels
 */
PCSCOM.prototype.setChatSize = function( width, height ){
	this._chatWidth = width;
	this._chatHeight = height;
}

/**
 * Sets the size of the popup window for the Mail client
 * @param width The width of the popup in pixels
 * @param height The height of the popup in pixels
 */
PCSCOM.prototype.setMailSize = function( width, height ){
	this._mailWidth = width;
	this._mailHeight = height;
}

/**
 * Sets the properties of the Mail tool
 * @param properties An array of properties to be set
 */
PCSCOM.prototype.setMailProperties = function( properties ){
	this._mailUrl =  ( (properties !== undefined) && (typeof properties.url == 'string') )? properties.url : this._mailUrl;
	this._mailWindowType =  ( (properties !== undefined) && (typeof properties.windowType == 'number') )? properties.windowType : this._mailWindowType;
	this._mailWidth = ( (properties !== undefined) && (typeof properties.width == 'number') )? properties.Width : this._mailWidth;
	this._mailHeight = ( (properties !== undefined) && (typeof properties.height == 'number') )? properties.Height : this._mailHeight;
}

