if (!window.ephip)
    window.ephip = {};

window.ephip.gateway = {

    jsonFormData: {},

    serviceRoot: "/API.svc",

    httpMethodType: { get: "GET", post: "POST", put: "PUT", del: "DELETE" },

    // to be set on bootstrap
    resourceActionMap: {
        membershipreneworjoin_post: {
            action: "/membership/reneworjoin",
            method: "POST"
        },
        membershipinquiry_post: {
            action: "/membership/inquiry",
            method: "POST"
        },
        productrequest_post: {
            action: "/productrequest/create",
            method: "POST"
        }
    },

    convertFormToJson: function (frm) {
        var fqfa = this.getFullyQualifiedFormAction(frm);
        this.jsonFormData[fqfa] = {};

        $(':input', frm).each(function (i, item) {
            if ($(item).attr("name") && $(item).attr("name") != "" && $(item).attr("ignoreSerialization") != "true") {
                if ($(item).attr("type") != "checkbox") {
                    switch ($(item).attr("dataType")) {
                        case "number":
                        case "num":
                            if ($(item).attr("type") == "radio" && item.checked)
                                ephip.gateway.setObjectProperty(ephip.gateway.jsonFormData[fqfa], item.name, Number($(item).val()));
                            else if ($(item).attr("type") != "radio")
                                ephip.gateway.setObjectProperty(ephip.gateway.jsonFormData[fqfa], item.name, Number($(item).val()));
                            break;
                        case "boolean":
                        case "bool":
                            if ($(item).attr("type") == "radio" && item.checked)
                                ephip.gateway.setObjectProperty(ephip.gateway.jsonFormData[fqfa], item.name, ($(item).val().indexOf("true") != -1));
                            else if ($(item).attr("type") != "radio")
                                ephip.gateway.setObjectProperty(ephip.gateway.jsonFormData[fqfa], item.name, ($(item).val().indexOf("true") != -1));
                            break;
                        default:
                            ephip.gateway.setObjectProperty(ephip.gateway.jsonFormData[fqfa], item.name, $(item).val());
                            break;
                    }
                }
                else if ($(item).attr("type") == "checkbox") {
                    ephip.gateway.jsonFormData[fqfa][item.name] = item.checked;
                }
            }

        });
        return this.jsonFormData[fqfa];
    },

    setObjectProperty: function (baseObject, propertyNameString, propertyValue) {
        var nestedProperties = propertyNameString.split('.');
        if (nestedProperties.length > 1) {
            var targetObject = baseObject;
            for (var i = 0; i < nestedProperties.length; i++) {
                if (i < (nestedProperties.length - 1)) {
                    if (!baseObject[nestedProperties[i]])
                        baseObject[nestedProperties[i]] = {};
                    baseObject = baseObject[nestedProperties[i]];
                }
                else
                    baseObject[nestedProperties[i]] = propertyValue;
            }
        }
        else
            baseObject[nestedProperties[0]] = propertyValue;
    },

    bindJsonToForm: function (data, resourceName) {
        var formId = "#" + resourceName + "Form";
        if ($(formId).length == 0)
            throw new Error("Form '" + formId + "' could not be located to bind data.");
        for (var prop in data) {
            var val = data[prop] || "";
            var formItemSelector = ":input[name='" + prop + "']";
            switch ($(formItemSelector, $(formId)).attr("type")) {
                case "radio":
                    var attValue = (val) ? "true" : "false";
                    $(formItemSelector + "[value='" + attValue + "']", $(formId))[0].checked = true;
                    break;
                case "checkbox":
                    $(formItemSelector, $(formId))[0].checked = val;
                    break;
                default:
                    $(formItemSelector, $(formId)).val(String(val));
                    break;
            }
        }
    },

    getResourceAction: function (dataContainer) {
        var resourceName = dataContainer.resourceName || $(dataContainer).attr("resourceName");
        var resourceMethod = dataContainer.resourceMethod || $(dataContainer).attr("resourceMethod");
        return this.resourceActionMap[resourceName.toLowerCase() + "_" + resourceMethod.toLowerCase()];
    },

    getFullyQualifiedFormAction: function (dataContainer) {
        var resourceName = dataContainer.resourceName || $(dataContainer).attr("resourceName");
        return location.href + resourceName;
    },

    formatActionRequestUri: function (requestAction, requestArgs) {
        if (requestArgs) {
            for (var prop in requestArgs) {
                requestAction = requestAction.replace("[" + prop.toLowerCase() + "]", requestArgs[prop]);
            }
            if (requestArgs.pg && requestArgs.pgSz) {
                requestAction += (requestAction.indexOf("?") == -1) ? "?" : "&";
                requestAction += "pg=" + requestArgs.pg + "&pgSz=" + requestArgs.pgSz;
            }
            if (requestArgs.sortBy) {
                requestAction += (requestAction.indexOf("?") == -1) ? "?" : "&";
                requestAction += "sortBy=" + requestArgs.sortBy;
            }
            if (requestArgs.sortMethod) {
                requestAction += (requestAction.indexOf("?") == -1) ? "?" : "&";
                requestAction += "sortMethod=" + requestArgs.sortMethod;
            }
        }
        return this.serviceRoot + requestAction;
    },

    getActionAjaxOptions: function (frmOrRequestData, requestArgs, successCallback, errorCallback) {
        try {
            if (frmOrRequestData.tagName) this.convertFormToJson(frmOrRequestData);
            var rsrcAction = this.getResourceAction(frmOrRequestData);
            if (!rsrcAction) throw new Error("Could not locate resource action.");
            var formattedRequestUri = this.formatActionRequestUri(rsrcAction.action, requestArgs);
            var ajaxOptions = {
                url: formattedRequestUri,
                type: rsrcAction.method,
                data: (frmOrRequestData.tagName) ? JSON.stringify(this.jsonFormData[this.getFullyQualifiedFormAction(frmOrRequestData)]) : JSON.stringify(frmOrRequestData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successCallback || this.defaultSuccessCallback,
                error: errorCallback || this.defaultErrorCallback
            }
            return ajaxOptions;
        }
        catch (ex) {
            alert(ex);
        }
    },

    makeRequest: function (options) {
        options.beforeSend = function (jqXHR, settings) {
            console.log("making request...");
            $('div.ajxldr').show();
        };
        options.complete = function (jqXHR, textStatus) {
            console.log("all requests complete...");
            $('div.ajxldr').hide();
            setTimeout(ephip.gateway.updatePageHeight, 250);
        };
        var sFn = options.success;
        options.success = function (data, status, xhr) {
            console.log("sucess - ending request...");
            sFn(data, status, xhr);
        };
        var eFn = options.error;
        options.error = function (xhr, status, error) {
            console.log("error - ending request...");
            eFn(xhr, status, error);
        };
        $.ajax(options);
    },

    updatePageHeight: function (additionalHeight) {
        if (!additionalHeight)
            additionalHeight = 0;
        $('div.appContent').css('height', 400);
        $('div.appContent').css('height', ($(document).height() - 65 + additionalHeight));
    },

    updatePageWidth: function (curView, additionalHeight) {
        if (!additionalHeight)
            additionalHeight = 0;
        if (curView.indexOf('musicsearch') > -1 || curView.indexOf('musictracks') > -1 || curView.indexOf('mytracks') > -1 || curView.indexOf('playlist') > -1 || curView.indexOf('membermanagement') > -1 || curView.indexOf('datamanagement') > -1 || curView.indexOf('emailmanagement') > -1 || curView.indexOf('pagemanagement') > -1)
            $('.viewContainer').css('width', 1500);
        else
            $('.viewContainer').css('width', 1000);
    },

    defaultSuccessCallback: function (data, status, xhr) {
        var test = "";
    },

    defaultErrorCallback: function (xhr, status, error) {
        try {
            var exception = (xhr.Message) ? xhr : eval("(" + xhr.responseText + ")");

            BB.messageWindow.show(exception.Message, { color: "red", "font-weight": "bold" });
        }
        catch (ex) { }
    },

    // Interface Enforcers
    Enforce_IRequestData: function (data) {
        if (!data.resourceName)
            throw new Error("Request data object does not implement the 'resourceName' property.");
        if (!data.resourceMethod)
            throw new Error("Request data object does not implement the 'resourceMethod' property.");
    },

    // FB Console Logging - setup for interoperability across non-supported browsers
    FBDebugPassthrough: function () {
        if (!window.console || !console.firebug) {
            var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
            window.console = {};
            for (var i = 0; i < names.length; ++i) {
                window.console[names[i]] = function () { }
            }
        }
    },

    // Misc Utils
    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 = $.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;
        }
    },

    getQSValue: function (key, q) {
        if (q && q.charAt(0) == "?")
            q = q.substring(1);
        else
            q = location.search.substring(1);
        var keyValuePairs = [];
        for (var i = 0; i < q.split("&").length; i++) {
            keyValuePairs[i] = q.split("&")[i];
        }
        for (var j = 0; j < keyValuePairs.length; j++) {
            if (keyValuePairs[j].split("=")[0] == key)
                return unescape(keyValuePairs[j].split("=")[1]);
        }
        return false;
    }

}

/*
IDF.prototype.getAjaxOptions = function(url, data, successCallback, errorCallback) {
    var ajaxOptions = {
        url: this.getUrlPrepend() + url,
        type: "POST",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: (successCallback) ? successCallback : this.successCallback(data),
        error: (errorCallback) ? errorCallback : this.errorCallback
    }
    return ajaxOptions;
}

IDF.prototype.Authenticate = function(frm, success, fail) {
    $.ajax(
        this.getAjaxOptions(
            this.svc.Authenticate,
            this.getSerializedFormData(frm, this.svc.Authenticate),
            success,
            fail
        )
    );
}

IDF.prototype.getException = function(dataObject) {
    var exception = (dataObject.Message)?dataObject:eval("(" + dataObject.responseText + ")");
    return exception;
}

IDF.prototype.setSessionCookie = function(uid) {
    var COOKIE_NAME = 'IDFSESSIONID';

    var expTime = new Date()
    var curdate = expTime.getTime()
    curdate += this.sessionExpires * 60 * 1000;
    expTime.setTime(curdate)

    //$.cookie(COOKIE_NAME, uid, { path: '/', expires: expTime });
    $.cookie(COOKIE_NAME, uid, { path: '/', expires: -1 });
    return this;
}

IDF.prototype.form2json = function(form, fn, returnAsObject, includeEmptyStringValues) {
    var fn = fn || function(data) { return data; };
    var data = {};

    $("input,select,textarea", form).each(function() {
        var element = $(this);
        if (element.attr("accept") === element.val()) {
			element.val('');
		}
        if ((element.attr("name") != "") && (includeEmptyStringValues || jQuery.trim(element.val()) != "")) {
			if(element.attr("type") != "checkbox"){
				data[element.attr("name")] = (typeof element.val() !== "string") ? element.val() : element.val().stripHTML();
			}
			else{ 
				// console.log("checkbox found");
				if(element.is(':checked') == true){
					// console.log("checkbox checked");
					if(data[element.attr("name")] == null){
						data[element.attr("name")] = [];
					}
					data[element.attr("name")].push(Number(element.val()));
				} 
			}
        }
    });

    data = fn(data);
    return (returnAsObject)?data:JSON.stringify(data);
}

String.prototype.stripHTML = function() {
	// What a tag looks like
	var matchTag = /<(?:.|\s)*?>/g;
	// Replace the tag
	return this.replace(matchTag, "");
}



IDF.prototype.getQuerystringValue = function queryString(key) {
	var page = new PageQuery(window.location.search);
	return unescape(page.getValue(key));
}

// Author: Peter A. Bromberg
QSUtil: function(q) {
	if (q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if (q) {
		for (var i = 0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for (var j = 0; j < this.keyValuePairs.length; j++) {
			if (this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for (var j = 0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}
*/
