﻿var authTimeoutTimer;
var clientAuthTimeout = 0;
var alertMsg1;
var alertMsg2;

function StartAuthTimeout(timeout, msg1, msg2) {
    
    //console.log("[StartAuthTimeout]");
    
    if (alertMsg1 == null)
        alertMsg1 = msg1;
    if (alertMsg2 == null)
        alertMsg2 = msg2;
    if (authTimeoutTimer != null)
        clearTimeout(authTimeoutTimer);
    if (timeout == null)
        timeout = clientAuthTimeout;
            
    authTimeoutTimer = setTimeout('OnClientAuthTimedout();', timeout);
    clientAuthTimeout = timeout;
}

function OnClientAuthTimedout() {
    var start = new Date();
    if (window.confirm(alertMsg1))
    {
        var stop = new Date();
        var diff = (stop - start) / 1000;

        if (diff < 120) {
            var proxy = new serviceProxy("WebServices/GothamTixWS.asmx/");
            proxy.invoke("WakeupServer", {}, null,
                function(result) { // success callback
                    StartAuthTimeout();
                },
                function(result) { // failure callback
                    OnWakeupServerFailure();
                }
            );
        }
        else {
            OnWakeupServerFailure();
        }

//        if (diff < 120) {
//            proxy.invoke("WakeupServer", {}, null,
//                function(result) { // success callback
//                    StartAuthTimeout();
//                },
//                function(result) { // failure callback
//                    OnWakeupServerFailureOnTime();
//                }
//            );
//            return;
//        }
//        else {
//            proxy.invoke("WakeupServer", {}, null,
//                function(result) { // success callback
//                    StartAuthTimeout();
//                },
//                function(result) { // failure callback
//                    OnWakeupServerFailureOutOfTime();
//                }
//            );
//        }
    }
    else {
        window.location.href = "Logout.aspx";
    }
}

function OnWakeupServerFailureOutOfTime() {
    window.location.href = "Logout.aspx";
}

function OnWakeupServerFailure() {
    window.alert(alertMsg2);
    window.location.href = "Logout.aspx";
}

function OnWakeupServerSuccess() {
    // do nothing
}

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_initializeRequest(InitializeRequestHandler);
prm.add_endRequest(EndRequestHandler);

function InitializeRequestHandler(sender, args)
{
    // do not allow processing a request if previous request is stil processing
    if (prm.get_isInAsyncPostBack())
    {
        arg.set_cancel(true);
 
        $("#processing").css("visibility","visible");
        return;
    }
}

function EndRequestHandler(sender, args)
{
    $("#processing").css("visibility","hidden");
}

$(document).ready(function(){
    var $btn = $('.form_submit');
    var $form = $btn.parents('.form');
    
    //console.log($btn, $form, $btn[0].type);

    $form.keypress(function(e){
        if (e.which == 13 && e.target.type != 'textarea') {
            if ($btn[0].type == 'submit')
            {
                //console.log('Submit clicked...');
                $btn[0].click();
            }
            else
            {
                //console.log('Eval...');
                eval($btn[0].href);
            }
            return false;
        }
    });
    
    $("input[type=button].close").click(function(){ window.close() });
    $("input[type=button].print").click(function(){ window.print() });
});

function toggleEventSummary(master, detail, eventId)
{
    // first child of master div is the image
    var src = $(master).children()[0].src;
    // switch image toggle sign
    if (src.endsWith("plus.png"))    
        src = src.replace('plus.png', 'minus.png');
    else
        src = src.replace('minus.png', 'plus.png');
        
    // third child of master div is the progress image
    var progress = $(master).children()[3];
    
    // if the detail DIV is empty initiate AJAX call, if not that means it's already been populated
    var obj = $(detail);
    if ($(detail).html() == "")
    {
        // show progress
        $(progress).css("display", "block");
        $(progress).css("margin-left", "15px");
        
        var year = $(":hidden[name$=hdfInventoryYear]").val();
        var month = $(":hidden[name$=hdfInventoryMonth]").val();
        
        // prepare parameters
        var params = '{eventId:"' + eventId + '", year:"' + year + '", month:"' + month + '"}';
        
        // issue AJAX call
        $.ajax({
                type: "POST", // set request type
                url: "WebServices/GothamTixWS.asmx/GetEventSummaryList", // set call to page method
                data: params, // set method params
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");},
                contentType: "application/json; charset=utf-8", // set content type
                dataType: "json", // set return data type
                success: function(msg, status) {
                    // hide progress
                    $(progress).css("display", "none");
                    $(master).children()[0].src = src;
                    $(detail).html(msg.d);
                    $(detail).slideToggle("normal");
                    },
                error: function(xhr, msg, e) {
                    // hide progress
                    $(progress).css("display", "none");
                    alert(msg);
                    }
                });                
    }
    else
    {
        $(detail).slideToggle("normal");
        //$(detail).html("");
        $(master).children()[0].src = src;
    }    
}

function highlightRow(obj, highlight)
{
    if (highlight)
    {
        $(obj).css("background-color", "white");
        $(obj).css("color", "black");
    }
    else
    {
        $(obj).css("background-color", "#828282");
        $(obj).css("color", "white");
    }
}

function showInventory(inventoryId) {
    window.location.href = "InventoryDetailsForm.aspx?action=update&id=" + inventoryId;
}

function DeleteThumbnail(eventOrVenue, thumbnailType, masterHolder) {

    // prepare parameters
    var params = '{eventOrVenue:"' + eventOrVenue +  '",thumbnailType:"' + thumbnailType + '"}';
    
    // issue AJAX call
    $.ajax({
        type: "POST", // set request type
        url: "WebServices/GothamTixImg.asmx/DeleteThumbnail", // set call to page method
        data: params, // set method params
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
        },
        contentType: "application/json; charset=utf-8", // set content type
        dataType: "json", // set return data type
        success: function() {
            artwork.removeImage(masterHolder);
        },
        error: function(xhr, msg, e) {
            // hide progress

            alert(msg);
        }
    });
}

function log(text) {
    var date = new Date();
    var dt = date.getMinutes() + ":" + date.getSeconds() + "." + date.getMilliseconds();
    $('#debug').find("div:last").append("<div>" + dt + " >> " + text + "</div>");

}

function clearLog() {
    $('#debug').find("div").remove();
}

/* Page Message Handling */
var pageMessage = 
{
    id : "#page-message",
    visible : false,
    message : "",
    init: function()
    {
        this.visible = false;
        this.message = "";
        
        $("#page-message").dialog({
            modal: true,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            autoOpen: false,
            autoResize: true,
            resizable: false,
            width: 500,
            height: 300,
            close: function() {
                pageMessage.visible = false;
            },
            title: "Information Panel"
        });
    },
    setMessage : function(msg, append)  
    {
        if (arguments.length > 1 && append && this.message.length > 0)
            pageMessage.message = pageMessage.message + "<br>" + msg;
        else
            pageMessage.message = msg;
    },
    show : function()
    {
        $(pageMessage.id).html(pageMessage.message);
        
//        if (this.visible)
//            $(this.id).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
//        else
//            $(this.id).fadeIn(800);
        
//        $("#page-message").dialog("open");
//       
        
        $("#page-message").dialog("open");
        if (this.visible)
            $(this.id).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
        else
            $(this.id).fadeIn(800);
        
        pageMessage.visible = true;
    },
    hide : function()
    {
        //$(this.id).fadeOut(800);
        $("#page-message").dialog("close");
        pageMessage.visible = false;
    },
    showMessage : function(msg)
    {
        pageMessage.setMessage(msg, false);
        pageMessage.show();
    }
};

$(function(){
    $("#page-message").click(function(){
        pageMessage.hide();
    });
});
/* End Page Message Handling */

/* Service Proxy */
var serviceProxy = function(serviceUrl, ignoreAuthTimeout)
{
    this.serviceUrl = serviceUrl;
    this.invoke = function(method, data, context, success, error)
    {
        var param = JSON2.stringify(data);
        var url = this.serviceUrl + method;
        
        // adjust the authentication timeout
        if (ignoreAuthTimeout == "undefined" || ignoreAuthTimeout == false)
            StartAuthTimeout();
        
        // issue AJAX call
        $.ajax({
            type: "POST", // set request type
            url: url, // set call to supplied url
            data: param, // set method params
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
            },
            contentType: "application/json; charset=utf-8", // set content type
            dataType: "json", // set return data type
            dataFilter: function (data, type) {
                return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
            },
            success: function(msg, status) {
                if (!success)
                    return;
                    
                success(msg.d, context);
            },
            error: function(xhr, msg, e) {
                if (!error)
                    return;
                    
                var err = JSON2.parse(xhr.responseText);
                error(err, context);
            }
        });
    }
}
/* End Service Proxy */

var validation =
{
    isNumeric: function(value) 
    { 
        if (value.match(/^\d+$/) == null) 
            return false; 
        else 
            return true; 
    }
};

/* Date Format */
/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

/* End Date Format */

var popup =
{
    openContent: function(fname) {
        var path = 'Content/' + fname;
        popup.open(path);
    },

    open: function(url) {
        window.open(url, 'popUpWindow', 'height=700, width=800, left=10, top=10, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=yes, directories=no, status=yes');
    },
    
    openPrivacyPolicy: function() {
        window.open("PrivacyPolicy.aspx", 'popUpWindow', 'height=700, width=1050, left=10, top=10, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=yes, directories=no, status=yes');
    },
    
    openOrderSummary: function(url) {
        window.open(url, 'popUpWindow', 'height=510, width=550, left=10, top=10, resizable=no, scrollbars=no, toolbar=no, menubar=no, location=no, directories=no, status=yes');
    },
    
    openEventDetailsToPrint: function(eventId)
    {
        window.open("PrintEventDetails.aspx?id=" + eventId, 'popUpWindow', 'height=560, width=610, left=10, top=10, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, directories=no, status=yes');
    },
    
    openReport: function(report)
    {
        window.open("ReportViewer.aspx?report=" + report, 'popUpWindow', 'height=800, width=1050, left=10, top=10, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, directories=no, status=yes');
    }
};


var artwork =
{
    img: function(container) {
        return $($(container).children()[0]); // first child of master div is the image
    },

    attach: function(container) {
        return $($(container).children()[2]); // 3rd child of master div is the 'Attach' link
    },

    rm: function(container) {
        return $($(container).children()[3]);  // 4th   child of master div is the 'Remove' link
    },

    viewFile: function(container) {
        return $($(container).children()[4]); // 5th  child of master div is the 'View File' link
    },

    bindViewFileLink: function(container) {
        this.viewFile(container).click(function() {
            popup.open(artwork.img(container).attr("alt"));
        });
    },

    bindAttachLink: function(container, frame) {
        artwork.attach(container).click(function() {
            $(frame).show();
            artwork.attach(container).hide();
            artwork.rm(container).hide();
        });
    },

    setContentLinks: function(container) {
        if (artwork.img(container).attr("src").length < 4) {
            artwork.rm(container).hide();
            artwork.viewFile(container).hide();
            artwork.img(container).hide();
        }
        else {
            artwork.img(container).show();
            artwork.rm(container).show();
            artwork.viewFile(container).show();
        }
    },

    setImage: function(container, file) {
        if (file.length < 1) 
        { 
            //artwork.img(container).hide();
            return; 
        } // no file was uploaded
        
        var names = file.split("|");
        this.img(container).attr("src", names[0]);
        this.img(container).attr("alt", names[1]);
        artwork.setContentLinks(container);
    },

    removeImage: function(container) {
        this.img(container).attr("src", "");
        this.img(container).attr("alt", "");
        this.img(container).hide();
        artwork.setContentLinks(container);
    },

    hideFrame: function(container, frame) {
        $(frame).hide();
        artwork.attach(container).show();
        artwork.setContentLinks(container);
    },

    frameOnLoad: function(container, frame) {
        artwork.bindViewFileLink(container);
        artwork.bindAttachLink(container, frame);
        artwork.hideFrame(container, frame);
        var fr = $(frame);
        var cd = (fr.get(0).contentDocument) ? fr.get(0).contentDocument : fr.get(0).contentWindow.document;
        if ($(cd).get(0).forms[0] == null) { return; }
        var result = $(cd).get(0).forms[0].elements["status"].value
        artwork.setImage(container, result);
    },
    resetImage: function(container, frame, url) 
    {
        var fr = $(frame);
        var cd = (fr.get(0).contentDocument) ? fr.get(0).contentDocument : fr.get(0).contentWindow.document;
        if ($(cd).get(0).forms[0] == null) { return; }
        $(cd).get(0).forms[0].elements["status"].value = url;
    }
};

/* Utilities */
$.fn.emptySelect = function() {
    return this.each(function() {
        if (this.tagName == 'SELECT') this.options.length = 0;
    });
}

$.fn.loadSelect = function(optionsDataArray) {
    return this.emptySelect().each(function() {
        if (this.tagName == 'SELECT') {
            var selectElement = this;
            $.each(optionsDataArray, function(index, optionData) {
                var option = new Option(optionData.caption, optionData.value);
                if ($.browser.msie) {
                    selectElement.add(option);
                }
                else {
                    selectElement.add(option, null);
                }                
            });
        }
    });
}