/*

Copyright (c) 2009 Anant Garg (anantgarg.com | inscripts.com)

This script may be used for non-commercial purposes only. For any
commercial purposes, please contact the author at 
anant.garg@inscripts.com

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/

var windowFocus = true;
var username;
var userid;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1500;
var maxChatHeartbeat = 35000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;
var ejecutivoid = 0;
var inizialized = false;

var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();
var chatNames = new Array();

document.initChat = function()
{
	jQuery(document).ready(function(){
			originalTitle = document.title;
			inizialized = true;
			startChatSession();
			jQuery([window, document]).blur(function(){
				windowFocus = false;
			}).focus(function(){
				windowFocus = true;
				document.title = originalTitle;
			});
		});
}

document.startChat = function()
{
	if(!inizialized) document.initChat();
	else chatWith(ejecutivoid);
}

function restructureChatBoxes() {
	align = 0;
	
	//MOD By staf621 for Mootools FIX
	//for (x in chatBoxes) {
	jQuery.each(chatBoxes, function(x,chatboxid){
		
		if (jQuery("#chatbox_"+chatboxid).css('display') != 'none') {
			if (align == 0) {
				jQuery("#chatbox_"+chatboxid).css('right', '20px');
			} else {
				width = (align)*(225+7)+20;
				jQuery("#chatbox_"+chatboxid).css('right', width+'px');
			}
			align++;
		}
	});
	//END of MOD
}

function chatWith(chatuserid) {
	createChatBox(chatuserid);
	jQuery("#rapidField_"+chatuserid).focus();
}

function createChatBox(chatboxid,minimizeChatBox) 
{
	if(typeof chatNames[chatboxid] == 'undefined' || chatNames[chatboxid] == '') return;
	
	if (jQuery("#chatbox_"+chatboxid).length > 0) {
		if (jQuery("#chatbox_"+chatboxid).css('display') == 'none') {
			jQuery("#chatbox_"+chatboxid).css('display','block');
			restructureChatBoxes();
		}
		jQuery("#rapidField_"+chatboxid).focus();
		return;
	}

	jQuery(" <div />" ).attr("id","chatbox_"+chatboxid)
	.addClass("chatBox")
	.html('<div class="chattextBox">'+
			'<div class="chatHead"><span class="chattittle" id="chattittle_'+chatboxid+'">'+chatNames[chatboxid]+'</span>'+
				'<a href="javascript:void(0)" class="closebutton" onclick="javascript:closeChatBox(\''+chatboxid+'\')"><img src="/images/chat/ico_closeuser.png"></a>'+
				'<a href="javascript:void(0)" class="minimize" onclick="javascript:toggleChatBoxGrowth(\''+chatboxid+'\')"><img src="/images/chat/ico_minuser.png"></a>'+
				'<div class="clear"></div>'+
			'</div>'+
			'<div class="chatBody">'+
				'<div class="MessageBox">'+
					'<div class="userMessages" id="userMessages_'+chatboxid+'">'+
					'</div>'+
					'<div class="scrollMessage" id="scrollMessage_'+chatboxid+'">'+
		            	'<div class="scrollBar" id="scrollBar_'+chatboxid+'"></div>'+
		            '</div>'+
		            '<div class="clear"></div>'+
				'</div>'+
				'<div class="myMessage">'+
					'<input class="rapidField" id="rapidField_'+chatboxid+'" type="text" value="" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxid+'\');"/><input type="button" class="rapidSend" value="" onclick="javascript:return checkChatBoxInputKey(null,jQuery(\'#rapidField_\'+chatboxid),\''+chatboxid+'\');"/>'+
				    '<div class="clear"></div>'+
				'</div>'+
				
			'</div>'+
		  '</div>')
	.appendTo(jQuery( "body" ));
	//<a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxid+'\')">-</a>
	//<textarea class="rapidField" id="rapidField_'+chatboxid+'" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxid+'\');"></textarea>
	//<input class="rapidField" type="text" value="Mensaje" /><input type="submit" class="rapidSend" value="" />
	/*
				'<div class="rapidAnswers">'+
					'<h1 class="rapidTittle">Respuestas Rápidas</h1>'+
					'<div class="rapidBox">'+
						'<div class="answers">'+
						    '<p><strong>¿Respuesta Rapida 1?</strong>Respuesta 1.</p>'+
						'</div>'+
						'<div class="scrollMessage" id="scrollMessageRapid_'+chatboxid+'">'+
							'<div class="scrollBar" id="scrollBarRapid_'+chatboxid+'"></div>'+
						'</div>'+
					'</div>'+
				'</div>'+
	*/
	jQuery("#chatbox_"+chatboxid).css('bottom', '0px');
	
	chatBoxeslength = 0;
	
	//MOD By staf621 for Mootools FIX
	//for (x in chatBoxes) 
	jQuery.each(chatBoxes, function(x,chatBox){
		if (jQuery("#chatbox_"+chatBox).css('display') != 'none') 
		{
			chatBoxeslength++;
		}
	});
	//END MOD by staf621
	

	if (chatBoxeslength == 0) {
		jQuery("#chatbox_"+chatboxid).css('right', '20px');
	} else {
		width = (chatBoxeslength)*(225+7)+20;
		jQuery("#chatbox_"+chatboxid).css('right', width+'px');
	}
	
	chatBoxes.push(chatboxid);

	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		if (jQuery.cookie('chatbox_minimized')) {
			minimizedChatBoxes = jQuery.cookie('chatbox_minimized').split(/\|/);
		}
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == chatboxid) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			jQuery('#chatbox_'+chatboxid+' .chatBody').css('display','none');
			//jQuery('#chatbox_'+chatboxid+' .chatboxinput').css('display','none');
		}
	}

	chatboxFocus[chatboxid] = false;

	jQuery("#rapidField_"+chatboxid).blur(function(){
		chatboxFocus[chatboxid] = false;
		jQuery("#rapidField_"+chatboxid).removeClass('rapidFieldselected');
	}).focus(function(){
		chatboxFocus[chatboxid] = true;
		newMessages[chatboxid] = false;
		//jQuery('#chatbox_'+chatboxid+' .chatboxhead').removeClass('chatboxblink'); //BLINK!!!!!!!!!!!!
		jQuery('#chatbox_'+chatboxid+' .chatHead').removeClass('chatboxblink');
		jQuery("#rapidField_"+chatboxid).addClass('rapidFieldselected');
	});

	jQuery("#chatbox_"+chatboxid).click(function() {
		if (jQuery('#chatbox_'+chatboxid+' .chatBody').css('display') != 'none') {
			jQuery("#rapidField_"+chatboxid).focus();
		}
	});
	
	jQuery("#chatbox_"+chatboxid).show();
	updateScrollbar($('userMessages_'+chatboxid),$('scrollMessage_'+chatboxid),$('scrollBar_'+chatboxid));
}


function chatHeartbeat(){

	var itemsfound = 0;
	
	if (windowFocus == false) {
 
		var blinkNumber = 0;
		var titleChanged = 0;
		for (x in newMessagesWin) {
			if (newMessagesWin[x] == true) {
				++blinkNumber;
				if (blinkNumber >= blinkOrder) {
					document.title = chatNames[x]+' dice...';
					titleChanged = 1;
					break;	
				}
			}
		}
		
		if (titleChanged == 0) {
			document.title = originalTitle;
			blinkOrder = 0;
		} else {
			++blinkOrder;
		}

	} else {
		for (x in newMessagesWin) {
			newMessagesWin[x] = false;
		}
	}

	for (x in newMessages) {
		if (newMessages[x] == true) {
			if (chatboxFocus[x] == false) {
				//FIXME: add toggle all or none policy, otherwise it looks funny
				//jQuery('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
				jQuery('#chatbox_'+x+' .chatHead').toggleClass('chatboxblink');
			}
		}
	}
	
	jQuery.ajax({
	  url: "/jchat/chatHeartbeat/_/"+((new Date()).getTime()),
	  //cache: false,
	  dataType: "json",
	  success: function(data) {

		jQuery.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxid = item.i;
				chatNames[chatboxid] = item.f;

				if (jQuery("#chatbox_"+chatboxid).length <= 0) {
					createChatBox(chatboxid);
				}
				if (jQuery("#chatbox_"+chatboxid).css('display') == 'none') {
					jQuery("#chatbox_"+chatboxid).css('display','block');
					restructureChatBoxes();
				}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					jQuery("#chatbox_"+chatboxid+" .userMessages").append('<div class="userText">'+
	                    '<p>'+item.m+'</p>'+
	                '</div>');
				} else {
					newMessages[chatboxid] = true;
					newMessagesWin[chatboxid] = true;
					if (!windowFocus) playAlert();
					jQuery("#chatbox_"+chatboxid+" .userMessages").append('<div class="adminText">'+
	                    '<h1 class="adminName">'+item.f+':</h1>'+
	                    '<p>'+item.m+'</p>'+
	                '</div>');
				}

				jQuery("#chatbox_"+chatboxid+" .userMessages").scrollTop(jQuery("#chatbox_"+chatboxid+" .userMessages")[0].scrollHeight);
				updateScrollbar($('userMessages_'+chatboxid),$('scrollMessage_'+chatboxid),$('scrollBar_'+chatboxid));
				itemsfound += 1;
			}
		});

		chatHeartbeatCount++;

		if (itemsfound > 0) {
			chatHeartbeatTime = minChatHeartbeat;
			chatHeartbeatCount = 1;
		} else if (chatHeartbeatCount >= 10) {
			chatHeartbeatTime *= 2;
			chatHeartbeatCount = 1;
			if (chatHeartbeatTime > maxChatHeartbeat) {
				chatHeartbeatTime = maxChatHeartbeat;
			}
		}
		
		setTimeout('chatHeartbeat();',chatHeartbeatTime);
	}});
}

function closeChatBox(chatboxid) {
	jQuery('#chatbox_'+chatboxid).css('display','none');
	restructureChatBoxes();
	inizialized = false;
	jQuery.post("/jchat/closeChat", { id: chatboxid, name: chatNames[chatboxid]} , function(data){	
	});
}

function playAlert()
{
	if(jQuery('#alert_span')[0]==null)
	{
		jQuery(" <span/>" ).attr("id","alert_span").appendTo(jQuery( "body" ));
	}
	jQuery('#alert_span').html("<embed src='/js/success.wav' hidden=true autostart=true loop=false>");
}

function toggleChatBoxGrowth(chatboxid) {
	if (jQuery('#chatbox_'+chatboxid+' .chatBody').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if (jQuery.cookie('chatbox_minimized')) {
			minimizedChatBoxes = jQuery.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxid) {
				newCookie += chatboxid+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		jQuery.cookie('chatbox_minimized', newCookie);
		jQuery('#chatbox_'+chatboxid+' .chatBody').css('display','block');
		//jQuery('#chatbox_'+chatboxid+' .chatboxinput').css('display','block');
		jQuery("#chatbox_"+chatboxid+" .userMessages").scrollTop(jQuery("#chatbox_"+chatboxid+" .userMessages")[0].scrollHeight);
		//jQuery("#chatbox_"+chatboxid+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxid+" .chatboxcontent")[0].scrollHeight); //SCOLL!
	} else {
		
		var newCookie = chatboxid;

		if (jQuery.cookie('chatbox_minimized')) {
			newCookie += '|'+jQuery.cookie('chatbox_minimized');
		}


		jQuery.cookie('chatbox_minimized',newCookie);
		jQuery('#chatbox_'+chatboxid+' .chatBody').css('display','none');
		//jQuery('#chatbox_'+chatboxid+' .chatboxinput').css('display','none');
		
	}
	
}

function checkChatBoxInputKey(event,chatboxtextarea,chatboxid) {
	 
	if(event ==null || (event.keyCode == 13 && event.shiftKey == 0))  {
		message = jQuery(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");

		jQuery(chatboxtextarea).val('');
		jQuery(chatboxtextarea).focus();
		//jQuery(chatboxtextarea).css('height','44px');
		if (message != '') {
			var chatName = chatNames[chatboxid];
			jQuery.post("/jchat/sendChat", {toid: chatboxid, to: chatName, message: message} , function(data){
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				jQuery("#chatbox_"+chatboxid+" .userMessages").append('<div class="userText">'+
                    '<h1 class="userName">'+username+':</h1>'+
                    '<p>'+message+'</p>'+
                '</div>');
                //<div class="chatboxmessage"><span class="chatboxmessagefrom">'++':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'++'</span></div>
				//jQuery("#chatbox_"+chatboxid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+username+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
				//jQuery("#chatbox_"+chatboxid+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxid+" .chatboxcontent")[0].scrollHeight);
				jQuery("#chatbox_"+chatboxid+" .userMessages").scrollTop(jQuery("#chatbox_"+chatboxid+" .userMessages")[0].scrollHeight);
				updateScrollbar($('userMessages_'+chatboxid),$('scrollMessage_'+chatboxid),$('scrollBar_'+chatboxid));
			});
		}
		chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;
		
		return false;
	}

	/*var adjustedHeight = chatboxtextarea.clientHeight;
	var maxHeight = 94;

	if (maxHeight > adjustedHeight) {
		adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
		if (maxHeight)
			adjustedHeight = Math.min(maxHeight, adjustedHeight);
		if (adjustedHeight > chatboxtextarea.clientHeight)
			jQuery(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		jQuery(chatboxtextarea).css('overflow','auto');
	}*/
	 
}

function noEjecutivosDisponibles()
{
	//alert('Por el momento no se encuentran ejecutivos disponibles, Intentalo de nuevo más tarde');
	window.location.href = '/contacto/noEjecutivos';
}

function startChatSession(){  
	jQuery.ajax({
	  url: "/jchat/startChatSession/_/"+((new Date()).getTime()),
	  //cache: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;
		userid = data.userid;
		ejecutivoid = data.ejecutivo_id;
		chatNames[ejecutivoid] = data.ejecutivo;
		
		jQuery.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxid = item.i;
				chatNames[chatboxid] = item.f;

				if (jQuery("#chatbox_"+chatboxid).length <= 0) {
					createChatBox(chatboxid,1);
				}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					//jQuery("#chatbox_"+chatboxid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
					jQuery("#chatbox_"+chatboxid+" .userMessages").append('<div class="userText">'+
	                    '<p>'+item.m+'</p>'+
	                '</div>');
				} else {
					//jQuery("#chatbox_"+chatboxid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
					jQuery("#chatbox_"+chatboxid+" .userMessages").append('<div class="adminText">'+
	                    '<h1 class="adminName">'+item.f+':</h1>'+
	                    '<p>'+item.m+'</p>'+
	                '</div>');
				}
			}
		});
		
		for (i=0;i<chatBoxes.length;i++) {
			chatboxid = chatBoxes[i];
			//jQuery("#chatbox_"+chatboxid+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxid+" .chatboxcontent")[0].scrollHeight);
			jQuery("#chatbox_"+chatboxid+" .userMessages").scrollTop(jQuery("#chatbox_"+chatboxid+" .userMessages")[0].scrollHeight);
			updateScrollbar($('userMessages_'+chatboxid),$('scrollMessage_'+chatboxid),$('scrollBar_'+chatboxid));
			setTimeout('jQuery("#chatbox_"+chatboxid+" .userMessages").scrollTop(jQuery("#chatbox_"+chatboxid+" .userMessages")[0].scrollHeight);', 100); // yet another strange ie bug
			//setTimeout('jQuery("#chatbox_"+chatboxid+" .chatboxcontent").scrollTop(jQuery("#chatbox_"+chatboxid+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
		}
	
	if(ejecutivoid>0)
	{
		chatWith(ejecutivoid);
	}
	if(ejecutivoid==-1)
	{
		noEjecutivosDisponibles();
	}
	else
	{
		setTimeout('chatHeartbeat();',chatHeartbeatTime);
	}
		
	}});
}


function updateScrollbar(content,scrollbar,handle,horizontal,ignoreMouse){
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	var slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			// Scrolls the content element in x or y direction.
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	})
	
	slider.set(slider.options.steps);
	if( !(ignoreMouse) ){
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	}
	// Stops the handle dragging process when the mouse leaves the document body.
	$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
