﻿//var domain = parent.location.protocol + '//' + window.location.hostname;
var domain = window.location.protocol + '//' + window.location.hostname; // Changed by Emre. Any changes please inform Emre...
var LivehelpDirect = domain + "/Livehelp/Livehelp.Direct/DirectService.asmx";

var livehelpLoaded = false;
var hostId = 0;
var stopTimer = false;

var timerDelegate;

var EHostStatus = { HOSTSTATUS_OFFLINE: 0, HOSTSTATUS_ONLINE: 1, HOSTSTATUS_BUSY: 2 };
var EAction = { ACTION_CHAT_IDLE: 0, ACTION_CHAT_REQUEST_BY_HOST: 1, ACTION_CHAT_REQUEST_BY_CLIENT: 2, ACTION_CHAT_ACCEPT_BY_HOST: 3, ACTION_CHAT_ACCEPT_BY_CLIENT: 4, ACTION_CHAT_DENY_BY_HOST: 5, ACTION_CHAT_DENY_BY_CLIENT: 6, ACTION_CHAT_WAITING: 7, ACTION_CHAT_EXIT: 8, ACTION_CHAT_CHATTING: 9 };

function Settings() {
	this.Enabled = false;
	
	this.WelcomeMessage = '';
	this.GoodbyeMessage = '';
	
	this.OfflineMessages = '';
	this.NotificationMailAddress = '';
	
	this.OnlinePicture = '';
	this.OfflinePicture = '';
	this.OccupiedPicture = '';
	this.WindowPicture = '';
}
var oSettings = new Settings();


function GetDetails() {
    var my_browser = BrowserDetect.browser + ' ' + BrowserDetect.version;
    var my_operatingSystem = BrowserDetect.OS;
    var my_resolution = screen.width + "x" + screen.height;
	var my_pageTitle = document.title;
	
    var config = {
        siteId: siteId
        , clientId: clientId
        , countryCode: my_countryCode
        , addressIP: my_addressIP
        , browser: my_browser
        , operatingSystem: my_operatingSystem
        , resolution: my_resolution
        , referrer: my_referringURL
		, pageTitle: my_pageTitle
		, isOldVisitor: my_IsOldVisitor
		, isChatBefore: my_IsChatBefore
    }

    return config;
}

function SetDetails() {
    config = GetDetails();

    var postData = {
        "jsonString": $.toJSON(config)
    };

    $.ajax({
        type: "POST"
		, url: LivehelpDirect + "/SetClientDetails"
		, data: postData
		, dataType: 'json'
		, success: function(result) {
			//var action = result.action;
		}
		, failure: function(data) {
			//console.log(Widgets_Global_server_cannot_be_established);
		}
    });
}


function GetLivehelpSettings() {
	var config = {
		siteId: siteId
		, clientId: clientId
	};
	var postData = {
		"jsonString": $.toJSON(config)
	};

	$.ajax({
		type: "POST"
		, url: LivehelpDirect + "/GetSettingsWeb"
		, data: postData
		, dataType: 'json'
		, success: function(result) {
			var jsonData = result.records;

			if(jsonData != null) {
				oSettings.LivehelpStatus = result.livehelpStatus;
				
				oSettings.WelcomeMessage = jsonData.WelcomeMessage;
				oSettings.GoodbyeMessage = jsonData.GoodbyeMessage;
				
				oSettings.OfflineMessages = jsonData.OfflineMessages;
				oSettings.NotificationMailAddress = jsonData.NotificationMailAddress;
				
				oSettings.OnlinePicture = jsonData.OnlinePicture;
				oSettings.OfflinePicture = jsonData.OfflinePicture;
				oSettings.OccupiedPicture = jsonData.OccupiedPicture;
				oSettings.WindowPicture = jsonData.WindowPicture;

                if (ThemeLiveHelpImagePaths.OnlinePicturePath) {
                    oSettings.OnlinePicture.Path = ThemeLiveHelpImagePaths.OnlinePicturePath;
                }
                
                if (ThemeLiveHelpImagePaths.OfflinePicturePath) {
                    oSettings.OfflinePicture.Path = ThemeLiveHelpImagePaths.OfflinePicturePath;
                }

                if (ThemeLiveHelpImagePaths.OccupiedPicturePath) {
                    oSettings.OccupiedPicture.Path = ThemeLiveHelpImagePaths.OccupiedPicturePath;
                }

				//Ext.get('imgOnlinePicture').dom.src = noPic;
				//Ext.get('imgOfflinePicture').dom.src = noPic;
				//Ext.get('imgOccupiedPicture').dom.src = noPic;
				//Ext.get('imgWindowPicture').dom.src = noPic;
				EvalLivehelpStatus(oSettings.LivehelpStatus);
			}
			else {
				$('#LivehelpPicture').css("display", "none");
				stopTimer = true;
			}
		}
		, failure: function(data) {
			//Timeout will remove client from list after XX seconds if this call fails & if user is not chatting. - Gkn
		}
	});
}

function EvalLivehelpStatus(livehelpStatus) {
    $('#LivehelpPicture').unbind('click'); //Unbind previous click events for only new one to work. - Gkn
    var domain2 = window.location.protocol + '//' + window.location.hostname;
	switch(livehelpStatus) {
		case 0:	//Offline
			$('#LivehelpPicture').attr("src", domain2 + oSettings.OfflinePicture.Path);
			$('#LivehelpPicture').click(function() {	//Add new click event handler. - Gkn
				LaunchForm();
			});
			break;

		case 1:	//Online
			$('#LivehelpPicture').attr("src", domain2 + oSettings.OnlinePicture.Path);
			$('#LivehelpPicture').click(function() {	//Add new click event handler. - Gkn
				BeginChat(true);
			});
			break;

		case 2:	//Busy
			$('#LivehelpPicture').attr("src", domain2 + oSettings.OccupiedPicture.Path);
			$('#LivehelpPicture').click(function() {	//Add new click event handler. - Gkn
				LaunchForm();
			});
			break;
	}
}

function ajaxCall(timer) {
	var path = (window.location.href) != '/' ? window.location.href : "home";
	var config = {
		siteId: siteId
		, clientId: clientId
		, location: "'" + path + "'"
		, pageTitle: "'" + document.title + "'"
	};
	var postData = {
		"jsonString": $.toJSON(config)
	};

	$.ajax({
	    type: "POST"
		, url: LivehelpDirect + "/ClientRegister"
		, data: postData
		, dataType: 'json'
		, success: function (result) {
		    if (!result) { return; }

		    var action = result.action;

		    //var jsonData = $.evalJSON(result.records);
		    var livehelpStatus = result.records.livehelpStatus;
		    var clientDetails = result.records.clientDetails;
		    hostId = result.records.hostId;

		    if (clientDetails == 0) {
		        SetDetails();
		    }

		    EvalLivehelpStatus(livehelpStatus);

		    switch (result.action) {
		        case EAction.ACTION_CHAT_CHATTING:
		            break;

		        case EAction.ACTION_CHAT_WAITING:
		            //Already accepted and waiting to fill in the form. Used for not to display chat request after each call. - Gkn
		            break;

		        case EAction.ACTION_CHAT_REQUEST_BY_HOST:
		            var config = {
		                siteId: siteId
						, hostId: hostId
						, clientId: clientId
						, action: EAction.ACTION_CHAT_WAITING
		            };
		            var postData = {
		                "jsonString": $.toJSON(config)
		            };

		            $.ajax({
		                type: "POST"
						, url: LivehelpDirect + "/ActionWeb"
						, data: postData
						, dataType: 'json'
						, success: function (result) {
						    //$.fn.ceebox.closebox();

						    SetFancyBoxStyles();

						    $("#grey_link").fancybox({
						        'overlayOpacity': 0.6,
						        'autoDimensions': false,
						        'autoScale': false,
						        'padding': 0,
						        'margin': 0,
						        'titlePosition': 'over',
						        'transitionIn': 'fade',
						        'transitionOut': 'fade',
						        'speedIn': 500,
						        'speedOut': 500,
						        'showCloseButton': false,
						        'width': 280,
						        'height': 160,
						        'type': 'iframe',
						        'titleShow': true
						    });

						    $('#grey_link').click();
						    //window.open("/Livehelp_ChatRequest.aspx","Incoming Chat Request","left=20,top=20,width=280,height=160,toolbar=0,resizable=0");
						}
						, failure: function (data) {
						    //console.log(Widgets_Global_server_cannot_be_established);
						}
		            });
		            break;
		    }
		}
		, failure: function (data) {
		    //console.log(Widgets_Global_server_cannot_be_established);
		}
	});
    if (!stopTimer) {
        timerDelegate = setTimeout("timerFunc()", 5000);
    }
}

function init() {
	ajaxCall();
    //$.timer(5000, function(timer) {
	//	if(stopTimer) timer.stop();
	//	ajaxCall();
    //});
	timerDelegate = setTimeout("timerFunc()", 5000);
}

function timerFunc() {
    ajaxCall();
}
function BeginChat() {
    $.fancybox.close();
    var queryString = '?SiteID=' + siteId + '&ClientID=' + clientId;
    window.open("/Livehelp/Livehelp/begin.aspx" + queryString, "LiveChat", "width=412, height=314, status=1, toolbar=0, location=1, resizable=0, menubar=0, scrollbars=0");
}

function LaunchForm() {
    $.fancybox.close();
    var queryString = '?SiteID=' + siteId + '&ClientID=' + clientId;
    window.open("/Livehelp/Livehelp/form.aspx" + queryString, "OfflineForm", "width=420, height=400, status=1, toolbar=0, location=1, resizable=0, menubar=0, scrollbars=0");
}

function DenyChat() {
    var config = {
        siteId: siteId
		, hostId: hostId
        , clientId: clientId
        , action: EAction.ACTION_CHAT_DENY_BY_CLIENT
    };
    var postData = {
        "jsonString": $.toJSON(config)
    };

    $.ajax({
        type: "POST"
        , url: LivehelpDirect + "/ActionWeb"
        , data: postData
        , dataType: 'json'
        , success: function(result) {
            switch (result) {
                case EAction.ACTION_CHAT_DENY_BY_CLIENT:
					//init();
					//$.fn.ceebox.closebox();
                    break;
                default:
                    break;
            }
        }
        , failure: function(data) {
            //console.log(Widgets_Global_server_cannot_be_established);
        }
    });
}

$(document).ready(function() {
	if(!livehelpLoaded) {
		livehelpLoaded = true;
		//$(".ceebox2").ceebox({ margin: 5, borderWidth: '0px', boxColor: '#333333', titles: false, overlayOpacity: 0.8 });
		//$(".ceebox2").ceebox({ margin: 5, borderWidth: '0px', titles: false, overlayOpacity: 0.8 });
		GetLivehelpSettings();
		init();
	}
});

function DeInit() {
	var config = {
		siteId: siteId
		, clientId: clientId
	};
	var postData = {
		"jsonString": $.toJSON(config)
	};
	$.ajax({
		type: "POST"
		, url: LivehelpDirect + "/ClientUpdate"
		, data: postData
		, success: function(result) {
			//No need for success messages. - Gkn
		}
		, failure: function(data) {
			//Timeout will remove client from list after XX seconds if this call fails & if user is not chatting. - Gkn
		}
	});
}

window.onbeforeunload = DeInit;
