$(document).ready(function() {
	
	$("a.anchorLink").anchorAnimate();
	
	getChat();
	
	$('.chatnow').click(function(){
		var datachat = $('select[name="cscrepresentative"]').val().split(',');
		if (datachat != 0 ) {
			openWindowChat(datachat[0],datachat[1],datachat[2]);
		} else {
			getChat();
		}
		return false;
	});

	$('#chatHelp').click(function(){
		manageContactsHelp();
	});
			
	function getChat(){
	
		var currentTime = new Date()
		var userID=$('#userID').html() 
		var window_chat;
		$.ajax({
			//url: 'http://192.168.21.143:8084/IBCChat/Rosters?callback=?',
			url: 'http://chat.ibcjapan.co.jp:8080/Chat/Rosters?callback=?',
			dataType: "jsonp",
			data: "&uid=" + userID + "&siteid=8",
			cache: false,
			success: function(data){
				var html = '';
				
				var cscSTRFav=""; 
				var cscSTR=''; 
					var cscSTRCnt=0;
					var cscSTRCntFav=0;
				
				var idirectSTRFav="";					
				var idirectSTR='';
					var idirectSTRCnt=0;
					var idirectSTRCntFav=0;
					
				var isInitiated;
				var isEmpty = (data.ROSTERS.ENTRY.length > 0 )?"1":"0";
				try { 
					isInitiated = (typeof data.ROSTERS.EVENT.REQUEST == 'undefined')?false:true;
				} 
				catch(e) { 
					isInitiated = false; 
				} 
				
				var servleturl = new servletURL();
				if(isInitiated){
					var _jid = data.ROSTERS.EVENT.REQUEST[0].USER.JID;
					var _jname = data.ROSTERS.EVENT.REQUEST[0].USER.NAME;
					var _userid = userID;
					var _deptId = servleturl.CSCGroupId;
					
					openNewWindow(_jid,_jname,_userid,_deptId,0);
				}
	
	
				/**Start Added for sorting AM's in chat**/
				//var DefaultJID = "storrefranca;cniere;gortiz;"; 
				//var JIDS = DefaultJID.toLowerCase().split(";");
				var DefaultJID = ""; 
				for(var counterX=1; counterX<3; counterX++)
				{
				 try {
					if( document.getElementById("ntName" + counterX).value != "NULL" )
					{
						DefaultJID = DefaultJID + document.getElementById("ntName" + counterX).value + ";"; 
					}
				 }
				 catch(e) {
				 }
				}
				
				var JIDS = DefaultJID.toLowerCase()
				
				/**End Added for sorting AM's in chat**/	


				$.each(data.ROSTERS.ENTRY, function(index,entry){
						
					if (entry['Groups'] != ""){
						$.each (entry['Groups'], function(entryindex,dataentry){
		
							//CSC
							if (dataentry == '808037'){								
								cscSTR += "<li class='databox'><a class='chatDatas' href='#' id='" + entry['JID'] + "," + entry['NAME'] + "," + dataentry +"'>" + entry['NAME']  + "</a></li>"
								cscSTRCnt++;
							}
							
						});
					}
					
				});
				
				html += ''
				

				//FOR ENGLISH TAB
				var  engTemplate,engTemplateFav;
				   
   				    engTemplate="";
				    engTemplateFav="";
					
					//THIS IS THE AVAILABLE PANEL
					
					var CSTemplate="";
					
					CSTemplate= CSTemplate +"<a href='#' id='CustomerService'>Customer Service (" + cscSTRCnt + ")</a>";
					CSTemplate = CSTemplate +"<div name='cscChat' ><ul>" + cscSTR + "</ul></div>";
					
					//alert(numArray.length);

					engTemplate=CSTemplate
					
				$('#availableContacts').html(engTemplate)
				
				$('a[id="edit"]').click(function(){
					strConcatManagedContacts();
				})
				
				$('.chatDatas').click(function(){
					var myString = this.id;

					var mySplitResult = myString.split(",");
						openWindowChat(mySplitResult[0],mySplitResult[1],mySplitResult[2])		
				})
				
				callChat();
			}
		});
		
	}

	
	function callChat(){
		setTimeout(function(){getChat()},30000);
	}
	
	function servletURL(){
		 this.popUpUrl = "chat.autoterminal.com";
		 this.folderPath = "Chat/";
		 this.serverPort = ":8080";
		 
		 //FOR ENGLISH MOTOHOUND
		 
		 this.CSCNewZealandGroupId = "808035";
		 this.CSCGroupId = "808002"; 
		 
		 this.IDIRECTTRANSGroupId = "808030";
		 this.ACCOUNTSGroupId = "808003";
		 this.SHIPPINGSGroupId = "808028";
		 this.PARTSGroupId = "808029";
		 this.PURCHASEGroupId = "808032";
		 
		 //FOR RUSSIA
		 this.RUSSIAGroupId="808020";
		 
		 //FOR SPANISH
		 this.SPANISHGroupId="808021";
		 
		 //FOR JAPANESE
		 this.JAPANDomesticGroupId="808026";

	}
	
	function openWindowChat(jid,jname,deptId){
		var servleturl = new servletURL();
		try {
		    var userid= $('#userID').html();
			var url = 'http://' + servleturl.popUpUrl + servleturl.serverPort +'/'+servleturl.folderPath+'index.jsp?siteid=8&user_id='+userid+'&uacc='+jid+'&un='+jname+'&deptId='+deptId;
 			var new_window = window.open(url,'CHAT_IBC','location=1,width=450,height=385');
 			if (window.focus) {
 				new_window.focus();
 			}
 		}catch(e){
 				alert("Exception thrown on Opening New Window : " + e.description);
		}
	}
	
	
	function openNewWindow(jid,jname,userid,deptId, force){
		var window_chat;
		var isICE;

		if (force == 0){
			isICE = 0;
		}else{
			isICE = 1;
			force = 1;
		}
		
		var servleturl = new servletURL();
		
		var url = 'http://' + servleturl.popUpUrl + servleturl.serverPort +'/'+servleturl.folderPath+'index.jsp?siteid=8&user_id='+userid+'&uacc='+jid+'&deptId='+deptId+"&ice=" + isICE;
		if (force == 1 || (!window_chat || window_chat.closed)) {
			try{
				window_chat = window.open(url,'CHAT_IBC','location=1,width=450,height=385');
				
				if(window_chat){
					window_chat.focus();
				}else{
					 //url="http://chat.ibcjapan.co.jp:8080/IBCChat/ICE?action=3&uid="+ userid + "&site=IBC";
					 $.ajax({
						url: "http://chat.autoterminal.com:8080/IBCChat/ICE",
						dataType: "jsonp",
						data: "action=3&uid=" + userid + "&site=IBC",
						cache: false,
						success: function(msg){}
					});

				}
			}catch(e) { 
				alert("Exception thrown on Opening New Window : " + e.description);
			}
		}else{
			if(window_chat) window_chat.focus();
		}
	}
		
	
	$('.chatlanguageBelow > li > a').click(function() 
		{
			var getEls = $('.chatlanguageBelow > li > a');
			for (var i=0; i<getEls.length; i++) 
			{
				$(getEls).removeClass('active');
			}
			$(this).addClass('active');
			 
			var representativeStr = $(this).attr("name");
			chat_TAB(representativeStr);
			
				
		});


});

$(window).unload( function () { 
	var userid= $('#userID').html();
	 $.ajax({
		url: "http://chat.autoterminal.com:8080/IBCChat/ICE",
		dataType: "jsonp",
		data: "action=3&uid=" + userid + "&site=IBC",
		cache: false,
		success: function(msg){}
	});
	//url="http://chat.ibcjapan.co.jp:8080/IBCChat/ICE?action=3&uid="+ userid + "&site=IBC";
});

function manageContact(strUser, strEmail, strSubject, strMessage, strCsite,favorites){
	var strUser= $('#userID').html();
	var sURL="http://chat.autoterminal.com:8080/PreferredContacts?userid="+ strUser;
	var isMozilla;
		isMozilla = (document.all) ? 0 : 1;	
	var newwin_chat;
		//var sURL="http://support.ibcjapan.co.jp/setcookie_csite.php?user="+strUser+"&email="+strEmail+"&subject="+strSubject+"&message="+strMessage+"&csite=104&deptid=2&favorites="+favorites
		
		if (!newwin_chat || newwin_chat.closed) {
			if (isMozilla) {       
				newwin_chat = window.open(sURL, 0, 'scrollbars=no,menubar=no,resizable=0,location=no,left=130,screenX=130,screenY=450,width=450,height=390' );
			}else{
				newwin_chat = window.open(sURL, 0, 'scrollbars=no,menubar=no,resizable=0,location=no,left=130,top=300,width=450,height=390' );
			}			
			if(newwin_chat) newwin_chat.focus();
		}
		else{
			if(newwin_chat) newwin_chat.focus();
		}
}

function manageContactsHelp () {
        var type = 'width=300,height=400,toolbar=0,resizable=0,scrollbars=1,status=0,directories=0,location=0'; // featured help
		var name = "Manage Contacts Help"
        var win = window.open("my_managecontacts.asp", name.replace(/\s+/g, "_"), type);
        win.focus();
        return false;
 }

jQuery.fn.anchorAnimate = function(settings) {

 	settings = jQuery.extend({
		speed : 100
	}, settings);	
	
	return this.each(function(){
		var caller = this
		$(caller).click(function (event) {	
		
			var locationHref = window.location.href;
			var elementClick = $(caller).attr("href");
			
			document.getElementById("chatlist").scrollTop = 0;
		
			var classData="";
			var hrefData="";
			var hrefSplitter="";
			classData=$(caller).attr("class");
			hrefData=$(caller).attr("href");
			hrefSplitter=$(caller).attr("href").split("_VS");
			//$(caller).attr("href",passData);
			hrefData= hrefSplitter[0];
			elementClick=hrefData
			//var destination = $( elementClick).offset().top;
			
			var posE = $(elementClick);
			var position = posE.position();
			
			if ($(elementClick).length > 0){
		
				$(".chatlist").animate({ scrollTop: position.top-72}, settings.speed, function() {
					//location.hash=elementClick
					
					if (classData.indexOf("CService")>=0){
						if (hrefData=="#CustomerService"){
							elementClick="#CustomerService_Favorite_VS_S";
						}else{
							elementClick="#CustomerService_VS_S";
						}
					}else if (classData.indexOf("IService")>=0){
						if (hrefData=="#IdirectTranslation"){
							elementClick="#IdirectTranslation_Favorite_VS_S";
						}else{
							elementClick="#IdirectTranslation_VS_S";
						}
					}else if (classData.indexOf("IParts")>=0){
						if (hrefData=="#Parts"){
							elementClick="#Parts_Favorite_VS_S";
						}else{
							elementClick="#Parts_VS_S";
						}
					}
					
					var VariableCheck=elementClick.split("_VS");
					var VariablehrefData= VariableCheck[0];
					
					if ($(VariablehrefData).length > 0){
						$(caller).attr("href",elementClick);
					}   
					//alert("--");
				});
			}
	
		})
	})
}

