﻿/// <reference path="jquery-1.3.2.js" />

var g_ObjectTracker = new Array();

var g_SubCommentMessageOffset = 2; // Number of sub message which server return on first load
var g_SubCommentMessageFetch = 5; // Number of sub message to return when "more comment" click

function HTMLEncode(text) {
    var re_nlchar;
    text = escape(text);
    if (text.indexOf('%0D%0A') > -1) {
        re_nlchar = /%0D%0A/g;
    } else if (text.indexOf('%0A') > -1) {
        re_nlchar = /%0A/g;
    } else if (text.indexOf('%0D') > -1) {
        re_nlchar = /%0D/g;
    }
    return unescape(text.replace(re_nlchar, '<br />'));
}

function getAppointmentCategoryName(cateID) {
    var cateName = "";
    cateID = cateID + "";
    switch (cateID){
        case "1":
            cateName = "Hangout";
            break;
        case "2":
            cateName = "Dinning";
            break;
        case "3":
            cateName = "Shopping";
            break;
        case "4":
            cateName = "Traveling";
            break;
        case "5":
            cateName = "Dating";
            break;
        case "6":
            cateName = "Happy Birthday";
            break;
        default:
            cateName = "Party Event";
            break;
    }

    return cateName;
}

function calculatePhotoSize(frameWidth, frameHeight, imageWidth, imageHeight){    
    if (imageWidth > frameWidth)
    {
        var newWidth = frameWidth;
        var aspect = imageHeight / imageWidth;
        //Calculate the new height using the aspect ratio and the desired new width.
        var newHeight = newWidth * aspect;
        
        return {'width':newWidth, 'height':newHeight};
    }
    return {'width':imageWidth, 'height':imageHeight};
}

function isPointInElement(x, y, divID) {
    var divPos = $("#" + divID).offset();

    divPos.right = divPos.left + $("#" + divID).outerWidth();
    divPos.buttom = divPos.top + $("#" + divID).outerHeight();
    if (x > divPos.left && x < divPos.right &&
        y > divPos.top && y < divPos.buttom) {
        return true;
    }
    return false;
}

//WrapText(text, จำนวนตัวอักษรต่อ 1 บรรทัด, จำนวนทั้งหมด)
function WrapText(text, charCnt, charLimit) {
    var out = "";
    var iStr = 0;
    if (undefined == charLimit) charLimit = 0;
    
    if (null == text) return "";
    if (0 != charLimit) {
        if (text.length > charLimit) {
            text = text.substr(0, charLimit) + "...";
        }
    }

    for (var i = 0; i < text.length; i++) {
        var charAti = text.charAt(i);
        if (" " == charAti) iStr = 0;
        else iStr++;

        out += charAti;
        
        if (iStr > charCnt) {
            out += "<br>";
            iStr = 0;
        }
    }

    return out;
}

//WrapText(text, จำนวนตัวอักษรต่อ 1 บรรทัด)
function WrapText2(text, charCnt) {
    var out = "";

    if (null == text) return "";

    for (var i = 0; i < charCnt; i++) {
        var charAti = text.charAt(i);
        out += charAti;
    }

    if (text.length > charCnt) out += "...";

    return out;
}

function InitUtil() {
    $("body").append('<div id="GlobalMessageBox" class="noticfication">' +
					 '   <h6>NOTIFICATION</h6>' +
					 '   <div class="bg_boxnoticfication">' +
					 '	    <p id="GlobalMessageBox_Message" class="yournote"></p><br>' +
					 '		    <center>' +
					 '          <input id="GlobalMessageBox_OK" type="button" value="OK" class="btn_popsend" />' +
					 '          </center>' +
					 '  </div>' +
					 '  <div class="bgpopup_bottom"></div>' +
				     '</div>');
    $("#GlobalMessageBox").dialog({ autoOpen: false, modal: true, dialogClass: 'igCustomDialog',
        draggable: false, width: 'auto', height: 'auto', resizable: false
    });
    $("#GlobalMessageBox").parent().attr("class", "igCustomDialog");
    $("#GlobalMessageBox_OK").click(function(e) { $("#GlobalMessageBox").dialog("close"); });

    $("body").append("<div id='ErrorMessageBox'></div>");
    $("#ErrorMessageBox").dialog({ autoOpen: false, modal: true, width: "600px" });

    $("body").append('<div id="ConfirmBox" class="noticfication">' +
					 '   <h6>NOTIFICATION</h6>' +
					 '   <div class="bg_boxnoticfication">' +
					 '	    <p id="ConfirmBox_Message" class="yournote"></p><br>' +
					 '		    <center>' +
					 '          <input id="ConfirmBox_OK" type="button" value="OK" class="btn_popsend" />' +
					 '		    <input id="ConfirmBox_Cancel" type="button" value="Cancel" class="btn_popcancel" />' +
					 '          </center>' +
					 '  </div>' +
					 '  <div class="bgpopup_bottom"></div>' +
				     '</div>');

    $("#ConfirmBox").dialog({ autoOpen: false, modal: true, dialogClass: 'igCustomDialog',
        draggable: false, width: 'auto', height: 'auto', resizable: false
    });
    $("#ConfirmBox").parent().attr("class", "igCustomDialog");
    $("#ConfirmBox_Cancel").click(function(e) { $("#ConfirmBox").dialog("close"); });

    //alert($("#ConfirmBox").parent().html());
    //.ui-widget-header { border: 1px solid #aaaaaa; background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; }
}

function WaitingBox(strMessage) {
    $("#GlobalMessageBox").dialog("close");
    $("#GlobalMessageBox_OK").css("display","none");
    $("#GlobalMessageBox_Message").text(strMessage); 
    $("#GlobalMessageBox").dialog("open");
}

function MessageBox(strMessage, objClass, onOkCallback, param) {
    $("#GlobalMessageBox_OK").show();
    $("#GlobalMessageBox_Message").text(strMessage);

    // Set OK callback
    var tempVar = null;

    if (undefined != objClass) {
        tempVar = new Object();
        tempVar.objClass = objClass;
        tempVar.onOkCallback = onOkCallback;
        tempVar.param = param;
    }

    $("#GlobalMessageBox_OK")
        .unbind('click')
        .bind('click', tempVar, function(e) {
            $("#GlobalMessageBox").dialog("close");
            if (null != e.data) {
                e.data.onOkCallback.call(e.data.objClass, e.data.param)
            }
        });

    $("#GlobalMessageBox").dialog("open");
}

function YesNoBox(strMessage, objClass, onOkCallback, param) {
    $("#ConfirmBox_Message").text(strMessage);
    $("#ConfirmBox").dialog("open");

    // Set OK callback
    var tempVar = new Object();

    tempVar.objClass = objClass;
    tempVar.onOkCallback = onOkCallback;
    tempVar.param = param;


    $("#ConfirmBox_OK")
        .unbind('click')
        .bind('click', tempVar, function(e) {
            $("#ConfirmBox").dialog("close");
            e.data.onOkCallback.call(e.data.objClass, e.data.param)
        });
}

function FindObjectInTracker(obj) {
    for (var i = 0; i < g_ObjectTracker.length; i++) { 
        //if(obj == g_ObjectTracker[i]) return  
    }
}

function AddObjectToTracker(obj) { 

}

var g_MessageMenuObject = null;
function RegisterMessageMenuObject(obj) {
    g_MessageMenuObject = obj;
}

function RefreshMessageMenuObjectMessageCount(obj) {
    if (null != g_MessageMenuObject) {
        g_MessageMenuObject.LoadMessageCount();
    }
}

var g_ActivityMessageObject = null;
function RegisterActivityMessageObject(obj) {
    g_ActivityMessageObject = obj;
}
function ReloadMessageInActivityMessage()
{
    if (null != g_ActivityMessageObject) {
        g_ActivityMessageObject.ReloadMessage();
    }
}

function GetURL(strTargetURL) {
    if (strTargetURL.substr(0, 2) == "//" ||
        strTargetURL.substr(0, 2) == "~/") {
        strTargetURL = strTargetURL.substr(2, strTargetURL.length - 2);
    } else if (strTargetURL.substr(0, 1) == "/") {
        strTargetURL = strTargetURL.substr(1, strTargetURL.length - 1);
    }
    return g_RootURL + strTargetURL;
}

function GetCurrentUserAccountID() {
    return g_AccountID;
}

function GetCurrentUserName() {
    return g_UserName;
}

function GetTargetUserAccountID() {
    return HTMLEncode(g_TargetAccountID);
}

function GetTargetUserName() {
    return HTMLEncode(g_TargetUserName);
}


function SendAjaxFromClass(url, obj, objClass,onSuccessCallback, param) {
    var data = "{}";
    if(obj != null) data = JSON.stringify(obj, function(key, value) { return value; });
    $.ajax({
        type: "POST",
        //data: "{'strMyNameFirstName':'" + strMyNameFirstName + "','strMyNameLastName':'strMyNameLastName'}",
        data: data,
        cache: false,
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if ("" != XMLHttpRequest.responseText) {
                //alert("Server error \r\n" + XMLHttpRequest.responseText);
                $('#ErrorMessageBox').dialog('option', 'buttons', { "Ok": function() { $(this).dialog("close"); } });
                $("#ErrorMessageBox").text(XMLHttpRequest.responseText);
                $("#ErrorMessageBox").dialog("open");
            }
        },
        success: function(response) {            
            onSuccessCallback.call(objClass, eval('(' + response.d + ')'), param);
        }
    });
}

function SendAjax(url, obj, onSuccess, async) {
    if(undefined == async || null == async){
        async = true;
    }
        
    var data = "{}";
    if(obj != null) data = JSON.stringify(obj, function(key, value) { return value; });
    
    $.ajax({
        type: "POST",
        cache: false,
        async: async,
        data: data,
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Server error \r\n" + XMLHttpRequest.responseText); },
        success: function(response) { onSuccess(eval('(' + response.d + ')')); }
    });
}

function AppendLoadingProgress(divID) {
    $("#" + divID).append("<center><div class='ajaxLoader' /></center>");
}
function RemoveLoadingProgress(divID) {
    $("#" + divID).find('.ajaxLoader').parent().remove();
}

function GetLoadingProgressUrl() {
    return g_RootURL + "App_Themes/SiteMasterTheme/Images/ajax-loader.gif";
}

function BindKeyEnter(id, func) {
    $('#' + id).keypress(
        function(e) {
            if (e.which == 13) {
                e.preventDefault();
                func(e);
            }
        });
    }

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/**
* 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;
    }
};