//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright © Sprawl Technologies Ltd. 2009 - All Rights Reserved
//
// Project      : MTV LIve Sharing
//                
// Description  : Main file containing integration with Live Messenger Web components
//
// File Name    : Umee.Client.MessengerIntegration.js
//                
// Author       : ATankov
//                   
// Revision     : 1
//                   
// Archive      : 
//                   
// LastMod      : 27 14:18 
//                   
// LastCheckin  : 27/08/09
//                   
// Log          : Added File Header
// 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var _user = null;
var _identity = null;
var _delAuthControl = null;
var _delegationToken = "";
var onlineContacts = [];
var offlineContacts = [];
var contactCollection = [];
var consentGenerated = false;
var messengerIns = null;
var currentUserAddress = "";
var videoID = "";
var carouselObj = null;
var conversationObject;
var isSignedIn = false;
var player = null;
var previousPlayerState = "paused";
var consent = null;
var barTag = null;
var currentConversations = [];
var isLiveButtonClicked = false;
var isLibraryLoaded = false;
var isIframeLoaded = false;
var isWebBarVisible = false;
var loadingDate = null;
var invokeDate = null;
var isSignedOutAfterLoad = false;
var datetimeLoaded = null;
var oldIframeLocation = "";

var isWebBarLoaded = false;
var isLiveButtonClicked = false;

function onScriptLoaded() {

}

function OnUILoaded() 
{
    datetimeLoaded = new Date();
  
    try {
        barTag = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('bar', { 'onconsentcompleted': 'ConsentCompletedCallback' });
        document.body.appendChild(barTag);
        HideWebBar();
        isWebBarLoaded = true;
        if (isLiveButtonClicked) { 
            var lvBtn = document.getElementById("FW_ContentAction2_1_liveButton");
            if (lvBtn) {
                LiveButtonClicked(lvBtn);
            }
        }
    }
    catch (e) 
    {
        // This error could appear onli in FF because tring to readd web bar.
    }
}

function PresenceRcvt(presence) {
    var prc = presence;
}


function HideWebBar() {
    var WebBarCollection = $(".MessengerBarControl");
    if (WebBarCollection) {
        var webBarControl = WebBarCollection[0];
        if (webBarControl) {
            webBarControl.style.marginBottom = "-44px";

           // set_cookie("webbarvisible", "false");
        }
    }
}


function ShowWebBar() {
    
    var WebBarCollection = $(".MessengerBarControl");
    if (WebBarCollection) 
    {
        var webBarControl = WebBarCollection[0];
        if (webBarControl) 
        {
            var hght = webBarControl.scrollHeight;
            $(webBarControl).animate({ marginBottom: "0px" }, 500);
            var today = new Date();
            set_cookie("webbarvisible", "true",today.getFullYear()+1,today.getMonth(),today.getDay(),"/",document.domain);
            
        }
    }

    var hideWebBar = document.getElementById("FW_ContentAction2_1_hideWebBar");
    if (hideWebBar) {
        hideWebBar.className = "";
    }
    
}

function SlideWebBarDown(sender) {
//Hide Contact list before sliding
    var contactListControls = $(".ContactListControl");
    if (contactListControls) {
        var contactListControl = contactListControls[0];
        if ((contactListControl.style.visibility == "visible") || (contactListControl.style.display == "inline")) {
            var contactsButtonCollection = $(".MessengerBarControl_ContactListArea")
            if (contactsButtonCollection) {
                var contactsButton = contactsButtonCollection[0];
                if (contactsButton) {
                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        var evt = document.createEventObject();
                        contactsButton.fireEvent('onclick', evt);
                    }
                    else {
                        var evt = contactsButton.ownerDocument.createEvent('MouseEvents');
                        evt.initMouseEvent('click', true, true, contactsButton.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        contactsButton.dispatchEvent(evt);
                    }
                }
            }         
        }
    }

    //Slide WebBar component down
    isWebBarVisible = false;
    var WebBarCollection = $(".MessengerBarControl");
    if (WebBarCollection) {
        var webBarControl = WebBarCollection[0];
        if (webBarControl) {
            var hght = webBarControl.scrollHeight;
            $(webBarControl).animate({ marginBottom: "-44px" }, 500);
            
        }
    }
    //Hide button
    var hideWebBar = document.getElementById("FW_ContentAction2_1_hideWebBar");
    if (hideWebBar) {
        hideWebBar.className = "logout-button-invisible";
    }
    var today = new Date();
    set_cookie("webbarvisible", "false",today.getFullYear()+1,today.getMonth(),today.getDay(),"/",document.domain);
    
}


Microsoft.Live.Core.Loader.load(["Messenger.Core"], onScriptLoaded);

function SignInCompletedCallback(sender, e) {
    if (_user) {
        isSignedIn = true;
        var contCollection = _user.get_contacts();

        ConstructOfflineContacts(contCollection);
        if (isLiveButtonClicked) {
            var contactsButtonCollection = $(".MessengerBarControl_ContactListArea")
            if (contactsButtonCollection) {
                var contactsButton = contactsButtonCollection[0];
                if (contactsButton) {
                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        var evt = document.createEventObject();
                        contactsButton.fireEvent('onclick', evt);
                    }
                    else {
                        var evt = contactsButton.ownerDocument.createEvent('MouseEvents');
                        evt.initMouseEvent('click', true, true, contactsButton.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        contactsButton.dispatchEvent(evt);
                    }
                }
            }
        }

        _user.get_offlineContacts().add_collectionChanged(OnOfflineContactsChanged);
        currentConversations = _user.get_conversations();
        _user.get_conversations().add_collectionChanged(ConversationCollectionChanged);

        var liveButton = document.getElementById("FW_ContentAction2_1_liveButton");
        if (liveButton) {
            liveButton.className = "live-button-in";
        }

        var logoutButton = document.getElementById("FW_ContentAction2_1_logoutButton");
        if (logoutButton) {
            logoutButton.className = "";
        }

        var liveButtonIn = document.getElementById("FW_ContentAction2_1_liveButton_in");
        if (liveButtonIn) {
            liveButtonIn.className = "";
        }

        var liveButtonOut = document.getElementById("FW_ContentAction2_1_liveButton_out");
        if (liveButtonOut) {
            liveButtonOut.className = "invisible";
        }

        var webBarVisibilityMode = get_cookie("webbarvisible");

        if (!isWebBarVisible) {
            if (webBarVisibilityMode == "true") {
                ShowWebBar();
            }
        }
    }
}

function OnOfflineContactsChanged(sender, e) {
    

    var offCollection = $(".ContactListControl_GroupContacts");
    if (!offCollection) {
        return;
    }

    var offlineContacts = _user.get_offlineContacts();
    var count = offlineContacts.get_count();

    ConstructOfflineContacts(offlineContacts);
}

function ConstructOfflineContacts(offCollection) {

    var groupsHolder = $(".ContactListControl_Contacts")
    if (groupsHolder) {

        var offlineHolder = null;
        
        offlineHolder = document.getElementById("offlineHolder");
        if (offlineHolder == null) {
            offlineHolder = document.createElement('div');
            offlineHolder.setAttribute('id', 'offlineHolder');
            groupsHolder[0].appendChild(offlineHolder);
        }
        offlineHolder.innerHTML = "";
        var divTile = document.createElement('div');
        divTile.setAttribute('class', 'offline-title');

        if (offlineHolder) {
            offlineHolder.appendChild(divTile);
        }

        var oImg = document.createElement('img');
        oImg.setAttribute('src', 'http://www.wlmessenger.net/api/3.10.4524.0001/resources/images/transparent.gif');
        divTile.appendChild(oImg);
        divTile.innerHTML += "<B>Offline</B>";

        $(divTile).bind("mouseenter mouseleave", function(e) {
            $(this).toggleClass("over");
        });

        $(divTile).bind("click", function(e) {
            var offlineList = document.getElementById("offlineList");
            $(offlineList).toggleClass("invisible");
            $(this).toggleClass("colapsed");
        });

        var count = offCollection.get_count();
        if (!count) {
            count = 0;
        }
        var offListContainer = document.createElement('div');
        offListContainer.setAttribute("id", "offlineList");
        if (offlineHolder) {
            offlineHolder.appendChild(offListContainer);
        }

        var decription = "";
        var thumbnail = "";

        var metaCollection = document.getElementsByTagName('meta');
        if (metaCollection) {
            for (var j in metaCollection) {
                if (metaCollection[j].name == "description") {
                    decription = metaCollection[j].content;
                }
                if (metaCollection[j].name == "thumbnail") {
                    thumbnail = metaCollection[j].content;
                }
            }
        }

        for (i = 0; i < count; i++) {
            try {
                var contactItem = offCollection.get_item(i);

                var offContactItem = document.createElement('div');
                offContactItem.setAttribute('class', 'offline-contact-item');
                offListContainer.appendChild(offContactItem);
                $(offContactItem).bind("mouseenter mouseleave", function(e) {
                    $(this).toggleClass("over");
                });

                //var stg = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('status', { 'cid': contactItem.get_cid(), 'mode': 'image' });
                var stg = document.createElement('img');
                stg.setAttribute('src', 'http://www.wlmessenger.net/api/3.10.4524.0001/resources/images/transparent.gif');
                stg.setAttribute('class', 'offline-bullet');
                stg.setAttribute('height', '16px');
                stg.setAttribute('width', '16px');
                offContactItem.appendChild(stg);
                var displayName = document.createElement('div');
                displayName.setAttribute('class', 'offline-name');
                offContactItem.appendChild(displayName);

                var linkForSend = window.location.href ;
                if (linkForSend.indexOf("s_cid") < 0) {
                    //TODO: Add code for other parameters
                    if (linkForSend.indexOf("?") > 0) 
                    {
                        linkForSend = linkForSend + "%26s_cid%3d303";
                    }
                    else 
                    {
                        linkForSend = linkForSend + "%3fs_cid%3d303";
                    }
                }
                else {
                    var urlParts = linkForSend.split("?");
                    if (urlParts.length > 1) {
                        var parametersString = urlParts[1];
                        var parameters = parametersString.split("&");
                        if (parameters.length > 1) 
                        {
                            var newParams = "";
                            for (k = 0; k < parameters.length; k++) 
                            {
                                if (parameters[k].indexOf("s_cid") >= 0) 
                                {
                                    newParams += "s_cid%3d303";
                                    if (k < (parameters.length - 1)) {
                                        newParams += "%26";
                                    }
                                }
                                else {
                                    var cpar = parameters[k]
                                    cpar = cpar.replace("=", "%3d")
                                    newParams += cpar;
                                    if (k < (parameters.length - 1)) {
                                        newParams += "%26";
                                    }
                                }
                            }
                            
                            linkForSend = urlParts[0] + "%3f"+newParams;
                        }
                        else {
                            linkForSend = urlParts[0] + "%3fs_cid%3d303";
                        }
                    }
                }
                
                var recipAddress = contactItem.get_currentAddress().get_address();
                var userDisplayName = contactItem.get_displayName();
                userDisplayName = userDisplayName.split('@')[0];
                var myDisplayName = this._user.get_displayName();
                var mtvContent = $('meta[name=mtv_st]').attr("content");
                var mailSubject = "";
                if (mtvContent == 'video') {
                    mailSubject = "Hello " + userDisplayName + ", you like the same stuff as " + myDisplayName + " does, right?!  Well " + myDisplayName + " really likes this " + decription + " video on MTV and he reckons you'll like it too.  Click " + linkForSend + " to watch it and help cement your friendship with " + myDisplayName + "...";
                }
                else {
                    mailSubject = "Hello " + userDisplayName + ", you like the same stuff as " + myDisplayName + " does, right?!  Well " + myDisplayName + " really likes this " + decription + " content on MTV and he reckons you'll like it too.  Click " + linkForSend + " to read it and help cement your friendship with " + myDisplayName + "...";
                }
                
                
                var mailtolink = "http://mail.live.com/default.aspx?rru=compose%3fto%3d" + recipAddress + "%26subject%3d" + myDisplayName + " shared " + decription + " with you via the MTV Messenger%26body%3d" + mailSubject + "&wa=wsignin1.0";
                displayName.innerHTML = "<a class=\"offline-name-link\" target=\"_blank\" href=\"" + mailtolink + "\">" + contactItem.get_displayName() + "</a>";
            }
            catch (e) {
            //Ignore error to continue generating other offline contacts 
            }
        }
    }

}

function OfflkineContactClicked(email, displayName) {
    var decription = "";
    var thumbnail = "";

    var metaCollection = document.getElementsByTagName('meta');
    for (var j in metaCollection) {
        if (metaCollection[j].name == "description") {
            decription = metaCollection[j].content;
        }

        if (metaCollection[j].name == "thumbnail") {
            thumbnail = metaCollection[j].content;
        }
    }

    var mailtolink = "javascript:mailto:" + email + "?subject=" + displayName + " shared " + decription + " with you via the MTV Messenger&body=" + displayName + " saw this and thought of you!" + decription + "<a href='http://messenger.mtv.co.uk/MTVPage/index.aspx'><img src=\"" + thumbnail + "\" alt=\"thumbnail\"/>click here to watch it</a>";
    var win = window.open(mailtolink, email);
    if (win && win.open && !win.closed) {
        win.close();
    }
}

function ConsentCompletedCallback(sender, e) {
    var consentToken = sender.get_consentToken();
    
    var iframeObject = document.getElementById("MessengerIntagration");
    if (iframeObject) {
        iframeObject.contentWindow.GetDelegationToken(consentToken); 
    }
}

function RefreshAfterConsentIsCot(delegationToken) {
    
}

function AuthenticationCompletedCallback(sender, e) {
    try {
        _user = sender.get_user();
    }
    catch (e) {
        alert("Error while authenticatiob user.");
    }
}

function GetInviter() {
    var strReturn = "";
    try {
        var strHref = window.location.href;
        if (strHref.indexOf("?") > -1) {
            var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
            var aQueryString = strQueryString.split("&");
            for (var iParam = 0; iParam < aQueryString.length; iParam++) {
                if (aQueryString[iParam].indexOf("inviter=") > -1) {
                    var aParam = aQueryString[iParam].split("=");
                    if (aParam[0] == "inviter")
                        strReturn = aParam[1];
                    break;
                }
            }
        }
    }
    catch (e) {
        //Ignore this error to get empty inviter.
        //This will cause to work in initial state.
    }
    return unescape(strReturn);
}

function ConversationCollectionChanged(sender, e) {
    if (e.get_action() == 0) 
    {
        //A new conversation has created
    
        //*******************************************************/
        //THIS is to attach change event of the conversation box
        //For each invitation link this snippet reworks it to open in current window.
        try 
        {
            var convFooterItems = $(".ConversationListControl_Item");
            if (convFooterItems) {
                for (var ind = 0; ind < convFooterItems.length; ind++) {
                    $(convFooterItems[i]).click(function() {
                        var conversationHistoryControls = $(".ConversationHistoryControl");
                        if (conversationHistoryControls) {
                            for (var i = 0; i < conversationHistoryControls.length; i++) {
                                var convHistory = conversationHistoryControls[i];
                                var historyItems = convHistory.getElementsByTagName('span');
                                if (historyItems)
                                    for (var j = 0; j < historyItems.length; j++) {
                                    var anchors = historyItems[j].getElementsByTagName('a');
                                    for (var k = 0; k < anchors.length; k++) {
                                        //if (anchors[k].href.indexOf('messemger.mtv.co.uk') > 0) {
                                        anchors[k].target = "_top";
                                        //}
                                    }
                                }
                            }
                        }
                    });
                }
            }
        }
        catch (e) 
        { 
            //When unhandled error accurs to continue reworking othe ritems.
        }
        //*******************************************************/
    
        var newElements = e.get_newItems();
        if (newElements.length > 0) {
            var newConv = newElements[0];
            newConv.add_messageReceived(MessageReceived);
            conversationObject = newConv;
            if (newConv.get_creator().get_cid() == _user.get_address().get_cid()) {

                var mtvContent = $('meta[name=mtv_st]').attr("content");

                var username = _user.get_displayName().split("@")[0];
                
                var linkForSend = window.location.href;
                if (linkForSend.indexOf("s_cid") < 0) {
                    
                    if (linkForSend.indexOf("?") > 0) {
                        linkForSend = linkForSend + "&s_cid=303";
                    }
                    else {
                        linkForSend = linkForSend + "?s_cid=303";
                    }
                }
                else {
                    var urlParts = linkForSend.split("?");
                    if (urlParts.length > 1) {
                        var parametersString = urlParts[1];
                        var parameters = parametersString.split("&");
                        if (parameters.length > 1) {
                            var newParams = "";
                            for (k = 0; k < parameters.length; k++) {
                                if (parameters[k].indexOf("s_cid") >= 0) {
                                    newParams += "s_cid=303";
                                    if (k < (parameters.length - 1)) {
                                        newParams += "&";
                                    }
                                }
                                else {
                                    newParams += parameters[k];
                                    if (k < (parameters.length - 1)) {
                                        newParams += "&";
                                    }
                                }
                            }
                            linkForSend = urlParts[0] + "?" + newParams;
                        }
                        else {
                            linkForSend = urlParts[0] + "?s_cid=303";
                        }
                    }
                }

                var textOfTheMessage = "";
                if (mtvContent == 'video') {
                    textOfTheMessage = username + " wants to share a video with you. Follow the link " + linkForSend + " to watch and discuss the video."
                }
                else {
                    textOfTheMessage = username + " wants to share a " + mtvContent + " with you. Follow the link " + linkForSend + " to read all about it."
                }   
                var messageObject = new Microsoft.Live.Messenger.TextMessage(textOfTheMessage, null);
                newConv.sendMessage(messageObject, null);
            }
        }
    }
    else if (e.get_action() == 1) {
        //Tahe ection when closing conversation.
    }
}

function MessageReceived(sender, e) {
    if (e.get_message().get_reloaded()) {
        /*************************************************************************************/
        //This is indication for an old mesage which was sent before the instance was created
        //Because IE is caching all this old messages and they are received after the
        //conversatin control is created from the desctop messenger client. This is confusing
        //the operation of synchronization so need to ignore all old messages
        /*************************************************************************************/
        return;
    }
    ShowWebBar();
}

function LiveButtonClicked(sender) {

    isLiveButtonClicked = true;
    if (!isWebBarLoaded) {
        return;
    }

    ShowWebBar();
    if (isSignedOutAfterLoad) {
        var currentTime = new Date();
        var momentLoading = datetimeLoaded;
        momentLoading.setTime(datetimeLoaded.getTime() + 3600000);
        var momentLoadingTicks = momentLoading.getTime();
        var currentTicks = currentTime.getTime();
        if (momentLoadingTicks < currentTicks) {
            window.location.reload();
            return;
        }
        
    }
    isSignedInVisible = true;
    isLiveButtonClicked = true;
    var signInHolder = $(".SignInControl");
    if (signInHolder) {
        var realSignInHolder = signInHolder[0];
        if ((realSignInHolder.style.visibility == "hidden") || (realSignInHolder.style.display == "none")) {
            isSignedInVisible = false;
        }
    }

    if (!isSignedInVisible) {
        if (!isWebBarVisible) {
            setTimeout("ShowContactsList();", 500);
            isWebBarVisible = true;
        }
        else {
            ShowContactsList();
        }
        
    }
    else {
        var signInCtrlCollection = $(".SignInControl_Button")
        if (signInCtrlCollection) {
            try {
                var signInButton = signInCtrlCollection[0];
                if (signInButton) {
                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        var evt = document.createEventObject();
                        signInButton.fireEvent('onclick', evt);
                    }
                    else {
                        var evt = signInButton.ownerDocument.createEvent('MouseEvents');
                        evt.initMouseEvent('click', true, true, signInButton.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        signInButton.dispatchEvent(evt);
                    }
                }
            }
            catch (e) {
                //alert("Error while attaching live button.")
            }
        }
    }
}

//function VerifyAndReloadIframe() {
//    //This function is to refresh the iframe so it could be with available AppVerifierToken

//    var domIFrame = document.getElementById("MessengerIntagration");
//    if (domIFrame) {

//        domIFrame.contentWindow.location.reload(true);
//        //domIFrame.contentWindow.RenewConsentToken();
//    }
//}

function ShowContactsList() 
{
    var convCtrlCollection = $(".ContactListControl");
    if (convCtrlCollection) {
        convCtrlCollection[0].style.visibility = "visible";
        convCtrlCollection[0].style.display = "inline";
    }
}

function LiveButtonOver(sender) {
    if (!_user) {
        var liveButton = document.getElementById("FW_ContentAction2_1_liveButton");
        if (liveButton) {
            liveButton.className = "live-button-over";
        }
    }
}

function LiveButtonOut(sender) {
    if (!_user) {
        var liveButton = document.getElementById("FW_ContentAction2_1_liveButton");
        if (liveButton) {
            liveButton.className = "";
        }
    }
}

function SignedOutHandler(sender) {
    isSignedOutAfterLoad = true;
    isLiveButtonClicked = false;

//    Microsoft.Live.Messenger.UI.Tags.TagsFactory.disposeTag(barTag);
//    document.body.removeChild(barTag);
//    barTag = null;
    
    var liveButton = document.getElementById("FW_ContentAction2_1_liveButton");
    if (liveButton) {
        liveButton.className = "";
    }

    var logoutButton = document.getElementById("FW_ContentAction2_1_logoutButton");
    if (logoutButton) {
        logoutButton.className = "logout-button-invisible";
    }

    var liveButtonIn = document.getElementById("FW_ContentAction2_1_liveButton_in");
    if (liveButtonIn) {
        liveButtonIn.className = "invisible";
    }

    var liveButtonOut = document.getElementById("FW_ContentAction2_1_liveButton_out");
    if (liveButtonOut) {
        liveButtonOut.className = "";
    }
}

function DelCookies() {
    var new_date = new Date()
    new_date = new_date.toGMTString()
    var thecookie = document.cookie.split(";")
    for (var i = 0; i < thecookie.length; i++) {
        var cookieName = thecookie[i].split("=");
        document.cookie = thecookie[i] + "; expires =" + new_date;

    }
}

function LogoutFromMessenger(sender) {

    var logoutFrm = document.getElementById("logoutIframe");
    if (logoutFrm) {
        document.body.removeChild(logoutFrm);
    }
    
    var ifrm = document.createElement("IFRAME");
    ifrm.setAttribute("src", "http://login.live.com/logout.srf");
    ifrm.setAttribute("id", "logoutIframe");
    ifrm.style.width = 1 + "px";
    ifrm.style.height = 1 + "px";
    document.body.appendChild(ifrm); 

    
    var signOutCtrlCollection = $(".ProfileControl_ExpandedSignOutLocal")
    if (signOutCtrlCollection) {
        try {
            var signOutButton = signOutCtrlCollection[0];
            if (signOutButton) {
                if (navigator.userAgent.indexOf("MSIE") >= 0) {
                    var evt = document.createEventObject();
                    signOutButton.fireEvent('onclick', evt);
                }
                else {
                    var evt = signOutButton.ownerDocument.createEvent('MouseEvents');
                    evt.initMouseEvent('click', true, true, signOutButton.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                    signOutButton.dispatchEvent(evt);
                }
            }
            HideWebBar();
            var hideWebBar = document.getElementById("FW_ContentAction2_1_hideWebBar");
            if (hideWebBar) {
                hideWebBar.className = "invisible";
            }  
        }
        catch (e) {
            //alert("Error while attaching live button.")
        }
    }
}

function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) 
{
    try 
    {
        var cookie_string = name + "=" + escape(value);

        if (exp_y) {
            var expires = new Date(exp_y, exp_m, exp_d);
            cookie_string += "; expires=" + expires.toGMTString();
        }

        if (path)
            cookie_string += "; path=" + escape(path);

        if (domain)
            cookie_string += "; domain=" + escape(domain);

        if (secure)
            cookie_string += "; secure";

        document.cookie = cookie_string;
    }
    catch (ex) { 
    
    }
}


function get_cookie(cookie_name) 
{
    try {
        var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

        if (results)
            return (unescape(results[2]));
        else
            return null;
    }
    catch (ex) {
     
    }
}    