﻿if (jsStartLoad('MinToolkit')) {

jsRequire('Utils');

// ====
// Taken from AjaxControlToolkit.Common.js
function setElementOpacity(element, value) {

    if (!element) {
        return;
    }
    
    if (element.filters) {
        var filters = element.filters;
        var createFilter = true;
        if (filters.length !== 0) {
            var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
            if (alphaFilter) {
                createFilter = false;
                alphaFilter.opacity = value * 100;
            }
        }
        if (createFilter) {
            element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (value * 100) + ')';
        }
    }
    else {
        element.style.opacity = value;
    }
}

// ====
// Min stuff with much hard coded

var faders = new Array();

function fader(id, element, duration, onEnd, start, finish) {

    this.id = id; this.element = element; this.onEnd = onEnd; this.start = start; this.finish = finish; this.step = 0;
    this.steps = duration * 25;
    this.timerId = 0;

    this.doFade = function() {
    
        setElementOpacity(this.element, this.start + (this.finish - this.start) * this.step / this.steps);
        
        if (++this.step == this.steps) {
            faders[this.id] = null;
            clearInterval(this.timerId);
            if (this.onEnd)
                this.onEnd();
        }
    }
}

function fade(element, duration, onEnd, start, finish) {
    var i = 0;
    for (; i < faders.length; i++) {
        if (!faders[i])
            break;
    }
    faders[i] = new fader(i, element, duration, onEnd, start, finish);
    faders[i].timerId = setInterval('faders['+i+'].doFade()', 40);
    i = i+1;
}


// ====
// Button Rollovers
// call BtnRoll(<img>, bool roll)
// img.src fn has -R added or removed, according to "roll" bool
function BtnRoll(img, roll) {
    img.src=img.src.replace(/(-R)*(\.[^\.]*)$/, (roll?'-R':'')+'$2');
}


// ====
// Hand rolled watermarks
// To add a watermark, declare a hidden or text input straight after the text
// or password input you want to watermark, and include in it the class "waterMark"

function wm(input, helper) {
	this.input = input;
	this.helper = helper;
	this.input.onblur = wm.unFocus; // shouldn't these be listeners instead?
	this.helper.onfocus = wm.focus;

	this.tryFocus = function(focus) {
	    var value = this.input.value.trim();
	    var mark = (!focus && (value == ''))
	    this.helper.style.display = (mark ? '' : 'none');
	    this.input.style.display = (mark ? 'none' : '');
	    if (focus) {
	        this.input.focus();
	    }
	}
}
wm.all = new Array();
wm.findMe = function (el) {
	for (var i = 0; i < wm.all.length; i++) {
		var marker = wm.all[i];
		if (marker.input == el || marker.helper == el) return marker;
	}
	return null;
}
wm.focus = function() {
	wm.findMe(this).tryFocus(1);
}
wm.unFocus = function() {
	wm.findMe(this).tryFocus(0);
}
wm.clean = function () {
	for (var i = 0; i < wm.all.length; i++) {
		wm.all[i].tryFocus(0);
	}
}
wm.setup = function() {
    // watermark input must be the very next input declared
    var inputs = document.getElementsByTagName('input');

    for (var i = 0; i < inputs.length - 1; i++) {
        var child = inputs[i], sib = inputs[i + 1];

        if ((sib.type == 'hidden' || sib.type == 'text') &&
	    	(sib.className.indexOf('waterMark', 0) >= 0) &&
			(child.type == 'text' || child.type == 'password')) {
            wm.all[wm.all.length] = new wm(child, sib);
            i++; // the watermark isn't going to have a watermark!
            if (!sib.form.wmListen) {
                sib.form.wmListen = 1;
                addListener(sib.form, 'submit', wm.clean);
            }
        }
    }
    for (var i = 0; i < wm.all.length; i++) {
        wm.all[i].tryFocus(0);
    }
}

// set up the watermarks when window finishes loading
addListener(window, '_domload', wm.setup);

// ====
// Draggable
// To make something draggable call Draggable
// If it contains an element of class "dragger" that
// element will be used as the handle, otherwise the
// whole thing is.

function Draggable(obj) {
    var dragger = firstClass(obj, 'dragger');
    if (!dragger) dragger = obj;
    if (dragger) {
        dragger.onmousedown = dragMe;
        dragger.style.cursor = 'move';
    }
    obj.draggable = true;
}

function UnDraggable(obj) {
    obj.onmousedown = null;
    dropListener(document, 'mouseup', dropMe);
    dropListener(document, 'mousemove', moveMe);
    obj.draggable = false;
}
// don't worry these vars and the document listeners are only active during the actual dragging
var dragObj, dragger, dragXoff, dragYoff;

function dragMe(e) {
    dragObj = myBox(this);
    dragger = this;
    dragger.style.cursor = 'default';
    if (dragObj) {
        dragXoff = mouseX - parseInt(dragObj.style.left);
        dragYoff = mouseY - parseInt(dragObj.style.top);
        addListener(document, 'mouseup', dropMe);
        addListener(document, 'mousemove', moveMe);
    }
    dragger.ondragstart = function() { return false; }; // stop drag obj ghost
    document.onselectstart = function() { return false; }; // stop text selection (ie)
    return false; // stop text selection (others)
}

function moveMe(e) {
    dragObj.style.left = (mouseX - dragXoff) + 'px';
    dragObj.style.top = (mouseY - dragYoff) + 'px';
}

function dropMe(e) {
    dragger.style.cursor = 'move';
    document.onselectstart = null;
    dragger.ondragstart = null;
    dropListener(document, 'mouseup', dropMe);
    dropListener(document, 'mousemove', moveMe);
}

// ====
// Popups

// PopIt(box, mode, atMouse, centre, draggable)
// box:     the div or whatever to pop up. must be class "box"
// modes:   0 fragile - will be unpopped by a click anywhere
//          1 normal - has to be unpopped manually
//          2 modal - sets a div class .modalMask behind
// atMouse: x,y will be mousepos otherwise will be window centre
// centre:  centre the div on x,y otherwise will be top left
// draggable: popup is draggable (see Draggable())
// el:		box positioned beneath element el if given
function PopIt(box, mode, atMouse, centre, draggable, el) {
    var ds = new WinSize();

    unPopFragile();
    if ((draggable || (mode > 0)) && isIe6) ie6SelectBug(box, 0);
    switch (mode) {
        case 0: fragileBox(box); break;
        case 2: maskBox(box); break;
    }
    box.popMode = mode;
    if (draggable) {
        Draggable(box);
        if (mode == 0) addListener(box, 'click', noBubble);
    }
    // set display so dimensions get calculated
    document.body.appendChild(box);
    box.style.visibility = 'hidden';
    box.style.display = 'block';

    var bw = box.offsetWidth;
    var bh = box.offsetHeight;

    if (el) {
        x = el.offsetLeft; y = el.offsetTop + el.offsetHeight;
        while (el.offsetParent) {
            el = el.offsetParent;
            x += el.offsetLeft;
            y += el.offsetTop;
        }
    }
    else if (atMouse) {
        x = mouseX; y = mouseY; // utils.js
    }
    else {
        x = ds.x + (ds.w / 2);
        y = ds.y + (ds.h / 2);
    }
    if (centre) {
        x -= bw / 2;
        y -= bh / 2;
    }
    // pull it back if it's gone over the edge
    if ((x + bw) > (ds.x + ds.w))
        x = ds.x + ds.w - bw;
    if ((y + bh) > (ds.y + ds.h))
        y = ds.y + ds.h - bh;
    box.style.left = x + 'px';
    box.style.top = y + 'px';
    box.style.visibility = 'visible';
}
function PopById(boxId, mode, atMouse, centre, draggable) {
    PopIt(ElId(boxId), mode, atMouse, centre, draggable);
}

// Close popup
function UnPop(box) {
    box.style.display = 'none';
    box.style.left = 0;
    box.style.top = 0;
    if ((box.draggable || (box.popMode > 0)) && isIe6) ie6SelectBug(box, 1);
    if (box.draggable)
        UnDraggable(box);
    if (box.myMask) {
        box.myMask.parentNode.removeChild(box.myMask);
        box.myMask = null;
    }
}

var isIe6 = false;
function ie6SelectBug(box, v) {
    var s = document.body.getElementsByTagName('select');
    for(var j=2; j>0; j--) {
        for (var i = 0; i < s.length; i++) {
            s[i].style.visibility = (v ? 'visible' : 'hidden');
        }
        s = box.getElementsByTagName('select');
        v = 1;
    }
}
var ie6Mask;
var ie6Listen;
function ie6Resize() { // ie6 only
    ie6Mask.style.height = document.body.parentNode.clientHeight;
    ie6Mask.style.top = document.documentElement.scrollTop;
    ie6Mask.style.left = document.documentElement.scrollLeft;
}

function maskBox(box) {
    if (!box.myMask) {
        var mask = document.createElement('div');
        var ch = document.body.parentNode.clientHeight;

        document.body.appendChild(mask);
        mask.className = 'modalMask';

        // nb for w&h, body must have margin 0 for xbrowser happiness
        if (mask.clientHeight < ch) { // ie6 position:fixed hack
            mask.style.position = 'absolute';
            mask.style.height = ch;
            ie6Mask = mask;
            if (!ie6Listen) {
                addListener(window, 'resize', ie6Resize);
                addListener(window, 'scroll', ie6Resize);
                ie6Listen = true;
            }
        }
        box.myMask = mask;
    }
    box.myMask.style.display = 'block';
}

var fragilePopup;

function fragileBox(box) {
    fragilePopup = box;
    box.notYet = true;
}

function unPopFragile() {
    if (fragilePopup) {
        if (fragilePopup.notYet)
            fragilePopup.notYet = false;
        else {
            UnPop(fragilePopup);
            fragilePopup = null;
        }
    }
}

addListener(window, '_domload', function() { addListener(document, 'click', unPopFragile); });

// ====
// Date Picker
// To Use: call DPPop() with an input element to be used for the date string
// Show a date picker using the value of, and positioned below, a given input field

// The css styles referenced are:
// whiteF - the fwd/back buttons
// popper - the main date popup
// box - the main date popup (needs this to be draggable)
// dragger - the date popup is draggable and has a dragger
// dpTitle - div at top shows MMM YYYY
// dpTd - unadorned date in the table
// dpSelected - selected date
// dpRollOn - date being rolled over
// note that dpSelected and dpRollOn elements are also class dpTd

// The poppup is fragile but traps clicks on itself. It adds a keydown listener to the
// input element for dismissing itself.
// The popup will be dismissed:
// - click anywhere else
// - type tab, enter or escape in the input box

// the box MUST be a table for ie<=7 to understand auto width
// also ie won't do setAttributes so using className and adding listeners

var dpBox;
var dpDays = ['Su','Mo','Tu','We','Th','Fr','Sa'];
var dpMonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

// Popup the date picker taking the given input box's value and position
function DPPop(dateInput) {
	var str=dateInput.value;
	var dpDate = StringToDate(str);
	if (!dpDate) {
		dpDate = new Date();
		dpDate = new Date(dpDate.getFullYear(), dpDate.getMonth(), dpDate.getDate()); // strip time
	}
	// Make the popup, if needed
	dpMkPicker();
	dpBox.dpDate = dpDate;
	dpBox.vwDate = null;
	dpBox.dpInput = dateInput;
	dpView(0);
	// The input box will cancel the picker if it gets a tab, enter or escape key
	addListener(dateInput, 'keydown', dpKeyDown);
	PopIt(dpBox, 0, 0, 0, 1, dateInput);
}
function dpUnpop() {
	if (dpBox) {
		dpBox.vwDate = null;
		dropListener(dpBox.dpInput, 'keydown', dpKeyDown);
		UnPop(dpBox);
	}
}
function dpMkPicker() {
	if (dpBox)
		return;
	var html;
	var el;
	var tr = document.createElement('tr');
	var td = document.createElement('td');
	var tb = document.createElement('tbody');
	var LT = '&LT;', GT = '&GT;', NB = '&nbsp;&nbsp;';
	var a1 = '<a href="#" onclick="dpView(';
	var a2 = '); return false;" class="whiteF">';
	var a3 = '</a>';

	td.colSpan = '7';

	// popper table
	dpBox = document.createElement('table');
	dpBox.className = 'popper box';
	dpBox.setAttribute('id', 'datePicker');

	// row 0: dragger
	el = document.createElement('div');
	el.className = 'dragger';
	el.innerHTML = NB;
	td.appendChild(el);
	tr.appendChild(td);
	tb.appendChild(tr);

	// row 1: dnButtons/title/upButtons
	// dnButtons
	td = td.cloneNode(false);
	tr = tr.cloneNode(false);
	el = document.createElement('div');
	el.style.cssFloat = 'left';
	el.style.styleFloat = 'left';
	html=a1+'-12'+a2+LT+LT+a3+NB;
	html+=a1+'-1' +a2+LT+a3;
	el.innerHTML = html;
	td.appendChild(el);
	// upButtons
	el = document.createElement('div');
	el.style.cssFloat = 'right';
	el.style.styleFloat = 'right';
	html= a1+'1' +a2+GT+a3+NB;
	html+=a1+'12'+a2+GT+GT+a3;
	el.innerHTML = html;
	td.appendChild(el);
	// title
	el = document.createElement('div');
	el.className = 'dpTitle';
	dpBox.dpTitle = el;
	dpBox.tb = tb;
	td.appendChild(el);
	tr.appendChild(td);
	tb.appendChild(tr);
	dpBox.appendChild(tb);
	//dpBox.tBodies[0].removeChild(dpBox.tBodies[0].rows[1]);
}
// Build the calendar table, set the m/y title
function dpView(offset) {
	var tr = document.createElement('tr');
	var tdMT = document.createElement('td');
	var tdEl = tdMT.cloneNode(false);
	var trTmp, tdTmp;
	var tb = dpBox.tb;
	var NB = '&nbsp;';
	var i, y, m, d, wd;
	var tmpDate;

	tdEl.className = 'dpTd';

	// strip off the existing calendar
	while (tb.rows.length > 2)
		tb.removeChild(tb.rows[2]);

	if (!dpBox.vwDate) dpBox.vwDate = new Date(dpBox.dpDate);
	dpBox.vwDate.setDate(1);
	with (dpBox.vwDate) {
		y = getFullYear();
		m = getMonth();
		d = 1;
	}
	// if offset given adjust viewDate
	if (offset) {
		m += offset;
		while (m < 0) {
			m += 12;
			y -= 1;
		}
		while (m > 11) {
			m -= 12;
			y += 1;
		}
		dpBox.vwDate = new Date(y,m,d);
	}
	tmpDate = new Date(dpBox.vwDate);
	wd = tmpDate.getDay();

	trTmp = tr.cloneNode(false);
	// Day name columns
	for (i=0; i<dpDays.length; i++) {
		tdTmp = tdMT.cloneNode(false);
		tdTmp.innerHTML = dpDays[i];
		trTmp.appendChild(tdTmp);
	}
	tb.appendChild(trTmp);
	trTmp = tr.cloneNode(false);
	tdMT.innerHTML = NB;
	// Leading blanks
	for (i=0; i<wd; i++) {
		trTmp.appendChild(tdMT.cloneNode(true));
	}
	// Month days
	while (m == tmpDate.getMonth()) {
		tdTmp = tdEl.cloneNode(false);
		addListener(tdTmp, 'click', dpPickDate);
		addListener(tdTmp, 'mouseover', dpRollOn);
		addListener(tdTmp, 'mouseout', dpRollOut);
		tdTmp.innerHTML = d;
		if (tmpDate.valueOf() == dpBox.dpDate.valueOf())
			tdTmp.className += ' dpSelected';
		trTmp.appendChild(tdTmp);
		tmpDate.setDate(++d);
		if (++wd > 6) {
			tb.appendChild(trTmp);
			trTmp = tr.cloneNode(false);
			wd = 0;
		}
	}
	if (wd) {
		while (wd++ <= 6) {
			trTmp.appendChild(tdMT.cloneNode(true));
		}
		tb.appendChild(trTmp);
	}
	dpBox.dpTitle.innerHTML = dpMonths[m] + ' ' + y;
}
function dpRollOn(e) {
	var el = (e.target ? e.target : e.srcElement);
	el.className += ' dpRollOn';
}
function dpRollOut(e) {
	var el = (e.target ? e.target : e.srcElement);
	el.className = el.className.replace(/\s*dpRollOn/, '');
}
function dpPickDate(e) {
	var el = (e.target ? e.target : e.srcElement);
	var day = el.innerHTML;
	with (dpBox) {
	    dpDate = new Date(vwDate.getFullYear(), vwDate.getMonth(), day);
		dpInput.value = DateToString(dpDate);
	}
	dpUnpop();
}
function dpKeyDown(e) {
    if (!e) e = window.event;
    if ((e.keyCode == 9) || (e.keyCode == 13) || (e.keyCode == 27)) {// tab, enter or escape
		dpUnpop();
    }
}

// ====
// Uploader
function uplCtx(form) {
    this.bar = firstClass(form, 'uplBar');
    this.fileLine = firstClass(form, 'idA');
    this.waitLine = firstClass(form, 'idB');
    this.prgLine = firstClass(form, 'idC');
    this.statusTxt = firstClass(form, 'idD'); // don't use 'status' it means something else
    this.fName = firstClass(form, 'uplFName');
    this.fileInp = form.elements['srcFile'];
    this.id = 0;
    this.extOK;
    this.errRq = 0;
    this.aborted = 0;
    this.cnt = 0;
    this.state = 0;
    form.ctx = this;
    // state 0 = show file input
    // state 1 = show spinning icon (started sending but no progress yet)
    // state 2 = show progress bar (sending and progress NZ)
    this.setState = function(s) {
        with (this) {
            if (s == state) {
                return;
            }
            state = s;
            //aborted = 
            errRq = 0;
            fileLine.style.display = (s == 0 ? '' : 'none');
            waitLine.style.display = (s == 1 ? '' : 'none');
            prgLine.style.display = (s == 2 ? '' : 'none');
            if (s == 0) {
                bar.style.width = '0';
                statusTxt.innerHTML = '';
                id = 0;
            }
        }
    }
}
function uplRqProgress(form) {
    if (form.ctx) with (form.ctx) {
        postRq('/Upload/Check' + (id ? ('?upl=' + id) : ''), uplGotProgress, form, null);
    }
}
function uplGotProgress(rq, form) {
    if (!form.ctx) {
        return;
    }
    with (form.ctx) {

        var upl;
        if (rq.status && (rq.status != 200)) {
            errRq++;
            statusTxt.innerHTML = 'error: ' + rq.status;
        }
        else {
            try {
                upl = eval('(' + rq.responseText + ')');
            }
            catch (e) {
                errRq++;
                statusTxt.innerHTML = 'error: malformed json';
            }
        }
        if (errRq) {
            if (errRq <= 2) { // Allow a few misses
                setTimeout(function() { uplRqProgress(form); form = null; }, 400);
            }
            else {
                UplAbort(form);
            }
            return;
        }

        var donePc = upl.DonePc + '%';
        var title;
        // For a new upload set up the form action and fire it
        if (!aborted && !id) {
            if (upl.HasErr) { aborted = 1; }
            else {
                form.action = '?upl=' + upl.Id;
                form.submit();
            }
            id = upl.Id;
        }
        bar.style.width = donePc;
        if (upl.Finished) {
            if (upl.HasErr && !aborted) {
                UplAbort(form); // If it was a server side error cancel client request
            }
            statusTxt.innerHTML = upl.StatusTxt;
            setState(2); // make sure StatusTxt is showing
            title = fName.innerHTML + ': ' + upl.StatusTxt;
            setTimeout(function() { setState(0); }, 2550);
        }
        else {
            if (!aborted) {
                statusTxt.innerHTML = ((++cnt % 2) ? '| ' : '- ') + donePc;
            }
            setState(upl.DoneB ? 2 : 1);
            title = fName.innerHTML + ': ' + donePc;
            setTimeout(function() { uplRqProgress(form); form = null; }, 400);
        }
        prgLine.title = prgLine.alt = fileLine.title = fileLine.alt = title;
    }
}
// pass checkFN to alert a warning if the file ext doesn't look right
function UplSetFN(form, checkFN) {
    var ctx = form.ctx;
    if (!ctx) {
        ctx = new uplCtx(form);
    }
    with (ctx) {
        var title = '';
        var goodExt = '*.flv, *.mov, *.wmv, *.avi, *.mpeg, *.mpg, *.mp4, *.jpg, *.tiff, *.tif, *.bmp, *.gif or *.png';
        var text = fileInp.value.split(/[\/\\]/).pop();
        var ext = text.split(/[\. ,\*]/).pop().toLowerCase();
        extOK = (ext.length >= 3) && goodExt.match(ext);
        if (extOK) {
            title = text + ': ready';
        }
        else {
            if (checkFN && text.length) {
                PopMsg('MeetSeeker Upload', 'Files must be one of the following types:\n' + goodExt + '\n(and have that filename extension)', 1);
                //PopInfo('MeetSeeker Upload', 'Files must be one of the following types:\n' + goodExt + '\n(and have that filename extension)');
                fileInp.value = '';
            }
            text = 'SELECT UPLOAD:';
            title = text;
        }
        fName.innerHTML = text;
        prgLine.title = prgLine.alt = fileLine.title = fileLine.alt = title;
    }
}
function UplStart(form) {
    var ctx = form.ctx;
    if (!ctx) {
        ctx = new uplCtx(form);
    }
    with (ctx) {
        aborted = 0;
        if (!fileInp.value || !extOK) {
            fName.innerHTML = 'No file selected!';
            setTimeout(function() { UplSetFN(form, 0); form = null; }, 1350);
        }
        else {
            setState(1);
            uplRqProgress(form);
        }
    }
}
function UplAbort(form) {
    var frm,cw;
    with (form) {
        if (ctx) {
            // Cancel upload at server and cancel request on client by sending new (blank) one to the same target
            ctx.statusTxt.innerHTML = 'stopping...';
            frm = ElId(target);
            frm.src = frm.src; // reload frame
/*
            cw = frm.contentWindow;
            try { frm.src = cw.location.href; }
            catch (err) { frm.src = frm.src; } // IIS 5.1 prefers
*/
            if (ctx.id && !ctx.aborted) {
                ctx.aborted = 1;
                postRq('/Upload/Abort?upl=' + form.ctx.id, 0, 0, 0);
            }
            setTimeout(function() { ctx.setState(0); }, 1350);
        }
    }
}

} //MinToolkit_js

