﻿var HuzuSocial = (typeof HuzuSocial !== "undefined") ? HuzuSocial : {};
var HuzuConstants = (typeof HuzuConstants !== "undefined") ? HuzuConstants : {};
    HuzuConstants.TempModalPopupId = "TempModalPopUp";

if(window.jQuery) $.ajaxSetup({ /* Disable caching of AJAX responses */cache: false });

(function (global, undefined) {

    var Huzu = global;

    /* HUZU UTILS */
    Huzu.Utils = {
        log: function () {
            if (console) {
                console.log(arguments);
            }
        },
        parseFunctionString: function(functionString, obj, args){
                        if(arguments[0].indexOf(".") !== -1){
                            var parts = functionString.split(".");
                            var newObj = obj[parts.shift()];
                            var newStr = parts.join(".");
                            return (typeof newObj === 'object' || typeof newObj === 'function')? arguments.callee(newStr, newObj, args) : false;
                        }else{
                         return obj[functionString];
                        }
        },
    dateFromISOString: function(isostr) {
        if(typeof isostr === "string"){
            isostr = isostr.replace(/\D/g," ");
            var date_parts = isostr.split(" ");
    	    return new Date(date_parts[0], date_parts[1] - 1, date_parts[2], date_parts[3] || 0, date_parts[4] || 0, date_parts[5] || 0);
        }
	},

    dateToISOString: function(dt) {
		if(typeof dt === "object"){
            var year, month, day, hours, mins, secs;
            var toDoubleDigits = function(date_part){
                return (date_part < 10)? "0"+ date_part : date_part;
                }
            year = dt.getFullYear();
            month = dt.getMonth()+1;
            date = dt.getDate();
            hours = dt.getHours();
            mins = dt.getMinutes();
            secs = dt.getSeconds();
    	    return year+"-"+toDoubleDigits(month)+"-"+toDoubleDigits(date)+"T"+toDoubleDigits(hours)+":"+toDoubleDigits(mins)+":"+toDoubleDigits(secs);
        }
	},

    toLocalTimeStamp: function(timestamp){
        var lts = "", dt = Huzu.Utils.dateFromISOString(timestamp), offset = dt.getTimezoneOffset()/60;
        dt.setHours((dt.getHours() - offset));
        lts = Huzu.Utils.dateToISOString(dt);
        return lts;
    },
	
	getRelativeTime: function(isostr){
	var now = new Date();
    var relativeTime = ((now - Huzu.Utils.dateFromISOString(isostr))/1000);
    
        var msg, val;
        switch(true) {
            case (relativeTime < 60):
            msg = "a moment ago";
            break;
            case (relativeTime > 60 && relativeTime < 3600):
            val = Math.floor(relativeTime / 60);
            msg = (val === 1)?  val + " minute ago" : val + " minutes ago";
            break;
            case (relativeTime > 3600 && relativeTime < 86400):
            val = Math.floor(relativeTime / 3600);
            msg = (val === 1)?  val + " hour ago" : val + " hours ago";
            break;
            default:
            val = Math.floor(relativeTime / 86400);
            msg = (val === 1)?  val + " day ago" : val + " days ago";
            break;
        } 
        
        return msg;
	},

        postJSON: function (url, data, callback) {
            $.ajax({
                type:"post",
                url: url,
                data: data,
                success: callback
            });
        },
        getJSON: function (url, data, callback) {
            $.ajax({
                type:"get",
                url: url,
                data: data,
                success: callback
            });
        },
        getMetaData: function (obj, attribute) {
            var str = $(obj).attr('meta');
            var meta = $.parseJSON(str);
            return meta[attribute];
        },

        sortBy: function (data, attrib) {
            var arr = data;
            var len = arr.length;
            for (var i = 0; i < (len - 1); i++) {
                for (var j = i + 1; j < len; j++) {
                    if (eval("arr[" + j + "]." + attrib) < eval("arr[" + i + "]." + attrib)) {
                        var temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            return arr;
        },

        FormManager: {
        getForm: function (param) {
        var type = typeof (param);
        var form;
        switch (type) {
            case "string":
                form = $("#" + param);
                break;
            case "object":
                var tagName = $(param).get(0).tagName.toLowerCase()
                form = tagName == "form" ? $(param) : $(param).parents('form:first');
                break;
        }
        return form;
    },
    postForm: function (form, callback) {
        var f = Huzu.Utils.FormManager.getForm(form);
        $.ajax({
            type:"post",
            url:f.attr("action"),
            context: form,
            data: f.serialize(),
            success: callback
        });
        return false;
    },
    postAndReplaceForm: function (form) {

        var f = Huzu.Utils.FormManager.getForm(form);
        $.ajax({
            type: "post",
            url: f.attr("action"), 
            data: f.serialize(), 
            success: function (html) {
                f.replaceWith(html);
            }
        });
        return false;
    }
},

DialogManager: {
    
    /* Private fields */
    _HuzuConfirmElementClicked: null,
    _HuzuConfirmDialog: null,

    postAndCloseDialog: function (form) {
        return Huzu.Utils.FormManager.postForm(form, function (html) {
            Huzu.Utils.DialogManager.closeAjaxDialog();
        });
    },
    ajaxPostAndReplace: function (url, data, jqElementToReplace, callback) {
        $.ajax({
            type:"post",
            url: url,
            date: data,
            success: function(html) {
                jqElementToReplace.replaceWith(html);
                if (typeof callback === "function") callback();
            }
        });
        return false;
    },
    ajaxGetAndReplace: function (url, data, jqElementToReplace, callback) {
        $.ajax({
            type:"get",
            url: url,
            date: data,
            success: function (html) {
                jqElementToReplace.replaceWith(html);
                if (typeof callback === "function") callback();
            }
        });
        return false;
    },
    getDimensions: function (dialog) {
        var jqObject = $("#jq-resize");
        var jqContainer = $(".ui-dialog-content");

        if (jqObject == null || jqObject.length == 0) {
            return;
        }

        var valueOf = function (element, css) {
            return Math.max(0, parseInt(element.css(css)) || 0);   // Performing a Math.max here as Chrome was reporting negative margins for some reason         
        }

        var element = jqObject,
        container = jqContainer,
        width = element.width(),
        height = element.height(),
        wpadding = valueOf(container, "padding-left") + valueOf(container, "padding-right") + valueOf(container, "margin-left") + valueOf(container, "margin-right"),
        hpadding = valueOf(container, "padding-top") + valueOf(container, "padding-bottom") + valueOf(container, "margin-top") + valueOf(container, "margin-bottom");

        dialog.height = height + hpadding;
        dialog.width = width + wpadding;


    },
    closeAjaxDialog: function () {
        $("#" + HuzuConstants.TempModalPopupId).remove();
    },
    showIFrameDialog: function (url, width, height) {
        Huzu.Utils.DialogManager.closeAjaxDialog();
        var html = "<div id=\"" + HuzuConstants.TempModalPopupId + "\" style=\"display:none;\"><div style=\"width=" + width + "px;height:" + height + "px;\">LOADING...</div></div>";
        $("body").append(html);

        var options = {
            resizable: false,
            position: "center",
            modal: true,
            width: width,
            height: height
        };

        $("#" + HuzuConstants.TempModalPopupId).dialog(options);
        $("#" + HuzuConstants.TempModalPopupId).html("<iframe src='" + url + "' width='" + width + "' height='" + height + "' />");
    },
    showAjaxDialog: function (url, data) {
        Huzu.Utils.DialogManager.closeAjaxDialog();
        var html = "<div id=\"" + HuzuConstants.TempModalPopupId + "\" style=\"display:none;\">LOADING...</div>";

        $("body").append(html);

        var options = {
            title: data.title || "",
            resizable: false,
            position: "center",
            modal: true,
            dialogClass: data.dialogClass || ""
        };

        if(data.width)
            options.width = data.width;

        $("#" + HuzuConstants.TempModalPopupId).dialog(options);

        $.ajax({
            type: "get",
            url: url,
            date: data,
            success: function(data){
        
            var html;
             if(typeof(data) === "object") {
                    html = data.Views[0];
                   
                }
                else{
                    //This code works for profile image upload.
                   html = data;
              
                    // Assuming a response starting with a "{" is JSON
                    if (typeof data === "string" && (data.indexOf("{") == 0 || data.indexOf("[") == 0)) {
                        var json = $.parseJSON(data);
                        html = json.Views[0];
                        }
                }
   
                Huzu.Utils.DialogManager.setAjaxDialogHtml(html);
                Huzu.Utils.DialogManager.autoResizeDialog();
            }
        });

        return false;
    },
    setAjaxDialogHtml: function (html) {
        $("#" + HuzuConstants.TempModalPopupId).html(html);

        Huzu.Utils.DialogManager.autoResizeDialog();
    },
    autoResizeDialog: function () {
        var dialog = new Object();

        dialog.width = -1;
        dialog.height = -1;

        Huzu.Utils.DialogManager.getDimensions(dialog);

        if (dialog.width > 0) {
            $("#" + HuzuConstants.TempModalPopupId).dialog("option", { width: dialog.width });
            $("#" + HuzuConstants.TempModalPopupId).dialog("option", { position: "center" });
        }
    },
    initConfirmations: function (selector, confirmText, callback, options) {

        // Check for stock callbacks
        if (callback == "close") // Perform confirmed action and simply close dialog
            callback = function (ele, dialog, json) { dialog.dialog("close"); };

        if (callback == "reload") // Perform confirmed action and reload the current page
            callback = function (ele, dialog, json) { window.location.reload(true); };

        callback = typeof (callback) != "undefined" ? callback : null;

        var defaults = {
                resizable: false,
                height: 'auto',
                dialogClass: "confirm-dialog",
                modal: true,
                buttons: {
                    "OK": function () {

                        // Get the ajax url using our convention
                        var ajaxUrl = Huzu.Utils.DialogManager._HuzuConfirmElementClicked.attr("data-ajax-url");

                        // Perform the ajax operation
                        Huzu.Utils.postJSON(ajaxUrl, {}, function (json) {

                            if (callback != null)
                                callback(Huzu.Utils.DialogManager._HuzuConfirmElementClicked, Huzu.Utils.DialogManager._HuzuConfirmDialog, json);

                            Huzu.Utils.DialogManager._HuzuConfirmElementClicked = null;
                            Huzu.Utils.DialogManager._HuzuConfirmDialog = null;
                        });
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                }
            };

        $.extend(defaults, options);

        $(selector).click(function () {
            // Hold a reference to the element that was originally clicked
            Huzu.Utils.DialogManager._HuzuConfirmElementClicked = $(this);

            // Create the confirm dialog html
            var dialogHtml = "<div style='display:none;'>" + confirmText + "</div>";

            // Create the actual dialog and hold a reference to it
            Huzu.Utils.DialogManager._HuzuConfirmDialog = $(dialogHtml).dialog(defaults);
        });
    }
}


    };

    /* HUZU MEDIA MANAGEMENT */
    Huzu.MediaManagement = {

    MediaItem: {
        deleteClickHandler: function (e) {
            e.preventDefault();
            Huzu.Utils.DialogManager.ajaxPostAndReplace(this.href, null, $(this).parents('li.widget'));
        },
        editClickHandler: function (e) {
            e.preventDefault();
            var modalOpts = {
                title: "Edit " + e.data.mediaType + " Properties"
            };
            Huzu.Utils.DialogManager.showAjaxDialog(this.href, modalOpts);
        },
        selectClickHandler: function (e) {
            e.preventDefault();
            var id = $(this).parents("li").attr("id");
            var mediaId = parseInt(id.substr(id.indexOf("_") + 1, id.length));
            FileBrowserDialogue.click(this.href, mediaId, this)
        }
    },

    ImageCropper: {
        cropImage: function (img, options) {

            $(img).Jcrop({
                minSize: options.minSize || 0,
                maxSize: options.maxSize || 0,
                onChange: function (coords) {
                    var img = $(".cropbox img:first");
                    if (typeof options.callback === "function") options.callback(coords);
                },
                onSelect: function (coords) {
                    var img = $(".cropbox img:first");
                    if (typeof options.callback === "function") options.callback(coords);
                },
                aspectRatio: options.aspectRatio
            });
        }
    }
}

return (window.Huzu = Huzu);

})(window.Huzu || {});


