﻿/// <reference path="jquery-1.3.2.js" />

// Define max value
var g_max_comment = 500;
var g_max_text = 250;
var g_max_tag = 50;
var g_max_place_entry_name = 100;
var g_max_place_entry_othername = 100;
var g_max_place_entry_howtogo = 4000;
var g_max_place_entry_desc = 4000;



var g_ObjectTracker = new Array();

function GetURL(strTargetURL) {
    if (null == strTargetURL) return "";
    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 IsAdmin() {
    if (g_admin == "True") return true;
    return false;
}

function IsLoggedIn() {
    if (GetCurrentUserAccountID() <= 0) return false;
    return true;
}

function GetCurrentUserAccountID() {
    return g_AccountID;
}

function GetCurrentUserName() {
    return g_UserName;
}

function GetCurrentUserAvatar() {
    return g_UserAvatar;
}

function GetTargetUserAccountID() {
    return g_TargetAccountID;
}

function GetTargetUserName() {
    return g_TargetUserName;
}



					
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;
}

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.substring(1, charLimit) + "...";
        }
    }

    for (var i = 0; i < text.length; i++) {
        if (" " == text[i]) iStr = 0;
        else iStr++;

        out += text[i];
        if (iStr > charCnt) {
            out += "<br>";
            iStr = 0;
        }
    }

    return out;
}


function InitUtil() {
    // GlobalMessageBox
    $("body").append('<div id="GlobalMessageBox">' +
					 '	    <p id="GlobalMessageBox_Message" ></p><br>' +
					 '		    <center>' +
					 '      <input class="liButton" id="GlobalMessageBox_OK" type="button" value="OK" />' +
					 '		    </center>' +
				     '</div>');
    $("#GlobalMessageBox").dialog({ autoOpen: false, modal: true, //dialogClass: 'igCustomDialog',
        draggable: false, width: '400px', height: 'auto', resizable: false
    });
    //$("#GlobalMessageBox").parent().attr("class", "igCustomDialog");
    $("#GlobalMessageBox_OK").click(function(e) { $("#GlobalMessageBox").dialog("close"); });

    // ErrorMessageBox
    $("body").append("<div id='ErrorMessageBox'></div>");
    $("#ErrorMessageBox").dialog({ autoOpen: false, modal: true, width: "600px" });

    // ConfirmBox
    $("body").append('<div id="ConfirmBox">' +
					 '<p id="ConfirmBox_Message"></p>' +
				     '</div>');

    $("#ConfirmBox").dialog({ autoOpen: false, modal: true, //dialogClass: 'igCustomDialog',
        draggable: false, width: '200px', height: 'auto', resizable: false,
        buttons: {
            "ยกเลิก": function() {
                $(this).dialog("close");
            },
            "ยืนยัน": function() {
                $(this).dialog("close");
                if (null != g_yesnobox_onOkCallback) {
                    g_yesnobox_onOkCallback.call(g_yesnobox_objClass, g_yesnobox_param);
                }
            }
        }
    });
    //$("#ConfirmBox").parent().attr("class", "igCustomDialog");
    
    //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_OK").css("display","none");
    $("#GlobalMessageBox_Message").text(strMessage); 
    $("#GlobalMessageBox").dialog("open");
}

function CloseWaitingBox() {
    $("#GlobalMessageBox").dialog("close");
}

function MessageBox(strMessage) {
    $("#GlobalMessageBox_OK").show();
    $("#GlobalMessageBox_Message").text(strMessage);
    $("#GlobalMessageBox").dialog("open");
}

var g_yesnobox_objClass = null;
var g_yesnobox_onOkCallback = null;
var g_yesnobox_param = null;

function YesNoBox(strMessage, objClass, onOkCallback, param) {
    $("#ConfirmBox_Message").text(strMessage);
    $("#ConfirmBox").dialog("open");

    g_yesnobox_objClass = null;
    g_yesnobox_onOkCallback = null;
    g_yesnobox_param = null;

    // Set OK callback
    g_yesnobox_objClass = objClass;
    g_yesnobox_onOkCallback = onOkCallback;
    g_yesnobox_param = param;
}




function NotifyBar(html, bAutoHide) {
    if (undefined == bAutoHide) bAutoHide = true;
    $.notifyBar({ html: html, bAutoHide: bAutoHide });
}

function FindObjectInTracker(obj) {
    for (var i = 0; i < g_ObjectTracker.length; i++) { 
        //if(obj == g_ObjectTracker[i]) return  
    }
}

function AddObjectToTracker(obj) {
    return g_ObjectTracker.push(obj);
}

var g_MessageMenuObject = null;
function RegisterMessageMenuObject(obj) {
    g_MessageMenuObject = obj;
}

function RefreshMessageMenuObjectMessageCount(obj) {
    if (null != g_MessageMenuObject) {
        g_MessageMenuObject.LoadMessageCount();
    }
}

function SendAjaxFromClass(url, obj, objClass,onSuccessCallback, param) {
    var data = "{}";
    if(obj != null) data = JSON.stringify(obj, function(key, value) { return value; });

    return $.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; });

    return $.ajax({
        type: "POST",
        cache: false,
        async: async,
        data: data,
        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);
            }
        },
        success: function(response) { onSuccess(eval('(' + response.d + ')')); }
    });
}

function AppendLoadingProgress(divID, loaderClass) {
    if (undefined == loaderClass) loaderClass = "ajaxLoader";
    $("#" + divID).append("<center><div class='" + loaderClass + "' /></center>");
}
function RemoveLoadingProgress(divID, loaderClass) {
    if (undefined == loaderClass) loaderClass = "ajaxLoader";
    $("#" + divID).find("." + loaderClass).parent().remove();
}

function GetLoadingProgressUrl() {
    //return g_RootURL + "App_Themes/SiteMasterTheme/Images/ajax-loader.gif";
    return g_RootURL + "App_Themes/WhereTheme/Images/where_loading.gif";
}

function BindKeyEnter(id, func) {
    $('#' + id).keypress(
        function(e) {
            if (e.which == 13) {
                e.preventDefault();
                func(e);
            }
        });
}

function BindKeyEnterFromClass(id, objClass, func) {
    $('#' + id).keypress(
        function (e) {
            if (e.which == 13) {
                e.preventDefault();
                func.call(objClass, e);
            }
        });
}

function nl2br(text) {
    var re_nlchar = null;
    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;
    }
    if (null != re_nlchar) return unescape(text.replace(re_nlchar, '<br />'));
    else return unescape(text);
}


var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function MaxLength(id, maxCharacters, paddingLeft) {
    if (undefined == paddingLeft) paddingLeft = "0px";
    // Should comment this line, it has effect with css. Caller should apply this style manually
    //$('#' + id).addClass("maxlength_textarea");
    $('#' + id).maxlength({
        maxCharacters: maxCharacters,
        statusClass: "maxlength_status",
        status: true,
        notificationClass: "maxlength_notification",
        slider: true,
        paddingLeft: paddingLeft
    });
}

function Redirect(href) {
    window.location.href = href;
}

function Reload() {
    window.location.reload();
}

