
/* global vars */
var g_isBrowserWinIE;
var g_modalDialog;



function registerToolTips() {

    // TODO - as jQuery extension methods
    $('select.infoTip, input.infoTip, textarea.infoTip').each(function(){
    var jq = $(this);
        
        var info = jq.attr('info');
        if(info && info.indexOf('|') > 0){
            var split = info.split('|');
            var anchor = $(doStringFormat("<a href=\"\" class=\"infoTip\" title=\"{0}|{1}\"></a>", split));
            jq.after(anchor);
            jq.css("float", "left");
        };
    });
    

    $('a.infoTip, .pipeTip, .helpTip, .helpTipSmall').each(function() {
        var jqt = $(this);
        if (jqt.attr('title').indexOf('|') > 0) {
            jqt.tooltip({
                delay: 0,
                showURL: false,
                showBody: '|'
            });
        };
    });

    $('.htmlTip').tooltip({
        bodyHandler: function() {
            var href = $(this).attr('href');
            return $(href).html();
        },
        showURL: false
    });
    
    
    

};

// generic element getter
function getElement(id)
{
	return document.getElementById(id);
};

// open a modal dialog for confirm pages
function openConfirmModalDialog(yesID, noID, url, frameSrc, useSecureConnection)
{	
	var yesCtrl = getElement(yesID);
	var noCtrl = getElement(noID);
	
	var retVal = openModalDialog(url, 860, 680, 200, 400, useSecureConnection, g_isBrowserWinIE);
	
	if(false == g_isBrowserWinIE && true == modalDialogSupported())
	{
		yesCtrl.checked = typeof retVal != 'undefined' && retVal != 'purchaseCancelled' ? retVal : false;
		noCtrl.checked = !yesCtrl.checked;
	}
	else
	{
		// no modal dialog - reset true / false here, page will be reloaded
		yesCtrl.checked = false;
		noCtrl.checked = true;
	}
};

// opens a modal dialog - works for mozilla and IE
// + url
// + width
// + height
// + top
// + left
// + useSecureConnection
// + nonModalOverride - if true, a non-modal dialog is used in this instance (e.g. if need to nav between pages in IE, or probs with https://)
function openModalDialog(url, width, height, top, left, useSecureConnection, nonModalOverride)
{	
	var result;
    
    if (false == nonModalOverride && true == modalDialogSupported())
    {
		if(g_isBrowserWinIE)
		{
			// host in iframe so we can nav between pages
			var dialogHost = useSecureConnection ? SECURE_HOST + APP_ROOT + 'modal_dialogs/md_hostmodaldialog.aspx' : APP_ROOT + 'modal_dialogs/md_hostmodaldialog.aspx';
		
			// get modal dialog (windows) features
			var features = 'resizable:no;scroll:yes;dialogWidth:' + width + 'px;dialogHeight:' + height + 'px;dialogTop:' + top + 'px;dialogLeft:' + left + 'px;';
			url = dialogHost + '?ifs=' + escape(url);
		
			result = window.showModalDialog(url, '', features);
			
        }
        else
        {
			var features = 'dialogwidth: ' + width + ';dialogheight: ' + height;
			result = window.showModalDialog(url, '', features);
        }
    }
    else 
    {
		
		if(g_modalDialog != null 
			&& typeof(g_modalDialog.close == 'function')){
			g_modalDialog.close();
		};
			
		var features = 'modal=yes,scrollbars=yes,directories=0,menubar=0,titlebar=0,toolbar=0,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;
		
		result = openWindow(url, features);
		
		g_modalDialog = result;
    };
    
    return result;
};

// are modal dialogs supported (e.g. window.showModalDialog)
function modalDialogSupported()
{
    // nb we are not supporting modals in FF3 due to problems with setTimeout and setInterval
    // see case 1643
    return true == g_isBrowserWinIE && typeof(window.showModalDialog) == 'function'; 
};

function openMediaShow(url, screenX, screenY)
{
	var popupWidth = 520;
	var popupHeight = 600;
	
	var top = screenY <= 0 ? 20 : screenY - (popupHeight / 2);
	var left = screenX <= 0 ? 20 : screenX - (popupWidth / 2);
	
	var features = 'scrollbars=1,modal=no,directories=0,menubar=0,titlebar=0,toolbar=0,width=' + popupWidth + ',height=' + popupHeight + ',top=' + top + ',left=' + left;
	return openWindow(url, features);
};

function openPurchaseWindow(url)
{
	return openModalDialog(url, 860, 680, 200, 400, true, g_isBrowserWinIE);
};

function openDonateWindow(url)
{
	var features = 'resizable=yes,scrollbars=yes,modal=no,directories=0,menubar=0,titlebar=0,toolbar=0,width=780,height=640,top=20,left=20';
	return openWindow(url, features);
};

function openWindow(url, features, windowName)
{
    features = typeof(features) == 'undefined' ? 'scrollbars=1,modal=no,directories=0,menubar=0,titlebar=0,toolbar=0,width=800,height=500,top=20,left=20' : features;
    windowName = typeof(windowName) == 'undefined' ? 'MuchLoved' : windowName;
	return window.open(url, windowName, features);
};

function openHelpPage(key, width, height, windowName)
{
	width = typeof(width) == 'undefined' ? 500 : width;
	height = typeof(height) == 'undefined' ? 500 : height;
	windowName = typeof(windowName) == 'undefined' ? 'Help' : windowName;

	var url = APP_ROOT + 'utils/help.aspx?ck=' + key;
	var features = 'scrollbars=1,modal=no,directories=0,menubar=0,titlebar=0,toolbar=0,width=' + width + ',height=' + height + ',top=5,left=600';
	openWindow(url, features, windowName);
};

function openHelpPageFromPopup(key)
{
    return openHelpPage(key, 500, 500, 'HelpFromPopup');
};


function openDonationsGalleryPopUp()
{
	var features = 'scrollbars=1,modal=no,directories=0,menubar=0,titlebar=0,toolbar=0,width=720,height=420,top=20,left=20';
	openWindow('d_donationsgallery.aspx', features);
};

function openDonationsSummaryPopup(url)
{
	openModalDialog(url, 360, 620, 20, 200, false, false);
};


function openTributeCostsPopup(url)
{
	var features;
	if (false == g_isBrowserWinIE)
		features = 'scrollbars=0,modal=yes,directories=0,menubar=0,titlebar=0,toolbar=0,width=570,height=540,top=20,left=200';
	else 
		features = 'scrollbars=0,modal=yes,directories=0,menubar=0,titlebar=0,toolbar=0,width=570,height=550,top=20,left=200';
	openWindow('../modal_dialogs/md_costs.aspx', features);
};

function openPreferredPartnerRequestPage()
{
	openHelpPage('preferredPartnerRequest', 600, 500);
};




// refreshes the current document
function reLoadPage(){
    document.location.href=document.location.href;
};

// refreshes the parent document
function refreshParent()
{
	var doc = isCurrentRequestInFrame() ? parent : document;
	doc.location.href = doc.location.href;
};

// reloads the parent document with the specified url
function reLoadParent(url)
{
	var doc = isCurrentRequestInFrame() ? parent : document;
	doc.location.href = url;
};

// reloads the frame with the specified inner frame source
function reLoadFrame(frameSource)
{
	url = 'frame.aspx?df=false&ifs=' + escape(frameSource);

	reLoadParent(url);
};

// reloads the player
function reLoadPlayer(frameSource, autoPlay)
{
	url = 'frame.aspx?ifs=' + escape(frameSource);
	
	reLoadParent(url);
};

// checks that the current request is in the frame, and reloads if not
function checkFrame(url)
{
	if(false == isCurrentRequestInFrame()) reLoadFrame(url);
};

// checks that the current request is not in the frame, and reloads if it is
function checkNoFrame(url)
{
	if(true == isCurrentRequestInFrame()) reLoadParent(url);
};

// returns a value indicating whether the current request is in the frame
function isCurrentRequestInFrame()
{
    var result = false;
	if(typeof parent != 'undefined')
	{
		result = (parent.getElement) && (null != parent.getElement('frame'))
	}
    return result;
};

// loads the login page from a tribute
function loginFromTribute(tributeID, email)
{
    var email = typeof(email) == 'undefined' ? '' : email;
    var url = SECURE_HOST + APP_ROOT + 'g_login.aspx?dlo=true&tid=' + tributeID + '&em=' + email;  // + '&returnUrl=' + escape(returnUrl);
	reLoadParent(url);
};

// reloads the opening window
function reLoadOpener(url){

	// if we can, reload the opener
	if(window.opener){
	
		// are we in the frame?
		var win = (typeof window.opener.parent != 'undefined') ? window.opener.parent : window.opener;
		
		var isUserMessagePage = win.location.href.indexOf('g_usermessage.aspx') != -1;
		
		if(true == isUserMessagePage)
		{
			win.location.href = 'frame.aspx?ifs=t_home.aspx';
		}
		else if(typeof url != 'undefined')
		{
			win.location.href = url;
		}
		else
		{
			win.location.href = win.location.href;
		}
	}

};

// do the modal dialog closing args. if modal dialog is supported, the return value is set,
// else we reload the opening window.
function doModalDialogClosingArgs(val)
{
	 if (!g_isBrowserWinIE && true == modalDialogSupported())
	 {
		window.returnValue = val;
	 }
	 else
	 {
		reLoadOpener();
	 }
};

/* cookie functions */
function getCookie(strCName){
	var strCookie=document.cookie;
	strCName = escape(strCName);
	var strCValue;
	var iStart=strCookie.indexOf(" " + strCName + "=");
	if(iStart==-1)
		{iStart=strCookie.indexOf(strCName + "=");}
	if(iStart==-1)
		{strCValue=null;}
	else{
		iStart=strCookie.indexOf("=",iStart)+1;
		var iEnd=strCookie.indexOf(";",iStart);
		if(iEnd==-1)
			{iEnd=strCookie.length;}
		strCValue=strCookie.substring(iStart,iEnd);
	}
	return unescape(strCValue);
};

function setCookie(strCName,strCValue,strCPath,dLife){
	
	if(document.cookie.length<=7300){
	
		if(typeof strCPath == 'undefined')
			strCPath = "/";
	
		if(typeof dLife == 'undefined')
			dLife = 1000;
	
		var ddate=new Date();
		ddate.setDate(ddate.getDate()+eval(dLife));
		dCExpires=ddate.toGMTString();
		document.cookie=escape(strCName)+"="+escape(strCValue)+";expires="+dCExpires+";Path="+strCPath+";";
	}
};

/* numeric only key press handler */
function onKeyPressNumericOnly(e)
{
	var key = getKey(e);
	
	if(key == 0 || key == 8)
	{
		// delete, back, ins etc.
		return true;
	}
	else
	{
		var val = String.fromCharCode(key);
		return val >= 0 && val <= 9;
	}
};

function trimToMaxLength(ctrl, maxLength)
{
	if(ctrl.value.length > maxLength)
	{
		ctrl.value = ctrl.value.substring(0, maxLength);
	}
};

function assertMaxLength(ctrl, maxLength, e)
{
	// prevent supression of back / delete keys
	var key = getKey(e);

	// delete, back, 
	return key == 0 || key == 8 || ctrl.value.length < maxLength;

};

function getRandom(from, to)
{
	var rand = Math.floor(Math.random() * to);
	return rand - from;
};


function changeImage(ctrlID, src) {
	var ctrl = getElement(ctrlID);
	if(ctrl && ctrl.src){
		ctrl.src = src;
	}
};

/* from CSCript lib (gateway funcs) */
function newImage(src) {
	if (document.images) {
		rslt = new Image();
		rslt.src = src;
		return rslt;
	}
};


function swapImage(ctrl, source)
{
	if(ctrl && ctrl.src){
		ctrl.src = source;
	}
};

/* media show opening */

var theOpenMediaShowWindow;

function doOpenMediaShow(groupID, e)
{

	if(typeof theOpenMediaShowWindow != 'undefined' && !theOpenMediaShowWindow.closed)
		theOpenMediaShowWindow.close();
	
	try
	{
		
		var inf = typeof(theSlideshow) != 'undefined' ? theSlideshow.getCurrentInfo().objectID : '';
		
		var url = 't_mediashow.aspx?iid=' + inf;
		
		if(typeof(groupID) != 'undefined')
		{
			url = url + '&gid=' + groupID;
		}
			
		theOpenMediaShowWindow = openMediaShow(url, e.pageX, e.pageY);
	}
	catch(exception)
	{
		theOpenMediaShowWindow = openMediaShow('t_mediashow.aspx', 100, 100);
	}
};


function isValidMoneyAmount(value)
{
	var re = new RegExp("^\-{0,1}((\\d+)|(\\d*\\.\\d{2}))$");
	return null != re.exec(value);
};

function ensure2TrailingDecimals(value)
{
	var re = new RegExp("\\.\\d{2}$");
	return null == re.exec(value) ? value + '.00' : value;
}

function isGuid(value)
{
	var re = new RegExp("^(\\{){0,1}[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}(\\}){0,1}$");
	return null != re.exec(value);
};

function trimWithEllipse(value, maxLength)
{
	return value.length > maxLength ? value.substring(0, maxLength - 1) + '...' : value;
};

function getKey(e)
{
	var key = null;
	
	if(e && e.which)
		key = e.which;
		
	else if (event)
		key = event.keyCode;
		
	return key;
};

function disableButton(btn) {
    // btn.onclick = function(){return false;};
    // btn.enabled = false;
    btn.disabled = "disabled";
    btn.title = '';
    btn.href = '';
};

function doPrompt(html, onYesFn, onNoFn){

    $.prompt(html,{ 
	    buttons:{Yes:true, No:false},
	    callback: function(v,m){
    		
		    if(v){
			    onYesFn();
		    }
		    else{
                onNoFn();
		    };
	    }
    });



};

/* file upload */

function onBeforeFileUpload(supportedExtensions, controlID, labelID, buttonID, errorMessage, waitMessage)
{
    var result = false;
	var fileName = $('#' + controlID).val();
	for(var i = 0; i < supportedExtensions.length; i++)
	{
		var re = new RegExp(supportedExtensions[i], "i");
		if(re.test(fileName)){
		    var btn = $('#' + buttonID);
		    btn.fadeOut(1000, function(){
    		    btn.before("<span class=\"greenText\">" + waitMessage + "</span>");
		    });
		    result = true;
		    break;
		};
	};
	
	var lbl = $('#' + labelID);
	lbl.html(result ? "" : errorMessage);
	lbl.attr("class", "statusText");
	
	return result;
};

function getUploadFileNameWithoutExtension(controlID){
    
    var result = $('#' + controlID).val();
    
    if(typeof(result) != 'undefined' && result.length > 0){
        
        var start = result.lastIndexOf('\\');
        var end = result.lastIndexOf('.');
        
        start = start == -1 ? 0 : start + 1;
        end = end == -1 ? result.length - start : end;
        
        result = (end > start && end <= result.length) 
                    ? result.substring(start, end) 
                    : result;
        
    };
    
    return result;
};

/* control detection functions */

function detectMediaPlayer()
{
	var result = detectPlugin('Windows Media Player');
    // if not found, try to detect with VBScript
    if(!result && g_isBrowserWinIE){
		result = detectUsingVBScript('MediaPlayer.MediaPlayer.1')
		        || detectUsingVBScript('WMPlayer.OCX');
    };
    return result;
};

function detectRealPlayer()
{
	var result = detectPlugin('RealPlayer');
    if(!result && g_isBrowserWinIE){
		result = detectUsingVBScript('rmocx.RealPlayer G2 Control') 
		        || detectUsingVBScript('RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)') 
		        || detectUsingVBScript('RealVideo.RealVideo(tm) ActiveX Control (32-bit)');
    };
    return result;
};

function detectFlash()
{
	var result = detectPlugin('Shockwave Flash');
    if(!result && g_isBrowserWinIE)
    {
        var MIN = 2;
        var MAX = 11;
		for (i = MIN; i < MAX; i++)
		{
			result = detectUsingVBScript('ShockwaveFlash.ShockwaveFlash.' + i);
			if(true == result) break;
		};
    };
    return result;
};

function detectPlugin(pluginName)
{
	var result = false;
	for (i = 0; i < navigator.plugins.length; i++)
	{
		result = navigator.plugins[i].name.indexOf(pluginName) >= 0;
		if(true == result) break;
	};
	return result;
};

// VB active x detection
if (true == g_isBrowserWinIE && typeof(detectActiveXControl) == 'undefined'){
    document.writeln('<script language="VBscript">');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('End Function');
    document.writeln('</script>');
};
function detectUsingVBScript(controlName){
    return g_isBrowserWinIE && detectActiveXControl(controlName);
};


function lineBreaksToBrTags(value){
    var pattern = /\n/g;
    return value.replace(pattern, '<br/>')
};

// qs //

function requestQuerystring(key){
    var re = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var results = re.exec( document.location.href );
    return results == null ? "" : results[1];
};

// string formatting
function doStringFormat(format, args){
    // props: http://frogsbrain.wordpress.com/2007/04/;28/javascript-stringformat-method/
    var pattern = /\{\d+\}/g;
    return format.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
};

// Array Remove - By John Resig (MIT Licensed)
// props: http://ejohn.org/blog/javascript-array-remove/
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

/* gardens manager */

function onGardensManagerHeadingChange(jqHeading, jqName){
    var heading = jqHeading.val().trim();
    if(heading.length > 0 && jqName.val().trim().length == 0){
        jqName.val(heading);
        onGardensManagerNameChange(jqName);
    };    
};
function onGardensManagerNameChange(jqName){
    jqName.val(jqName.val().replace(/\W/g, ''));
};

/* pods toolbar functions */

function initialisePodToolbar (parent, index, itemCount){
    // re-index the toolbar & functions
    parent.find('a.arrowUp').attr('href', 'javascript:onPodToolbar_moveUp(' + index + ');');
    parent.find('a.arrowDown').attr('href','javascript:onPodToolbar_moveDown(' + index + ');');
    parent.find('a.deleteButton').attr('href','javascript:onPodToolbar_delete(' + index + ');');
    parent.find('a.editButton').attr('href','javascript:onPodToolbar_edit(' + index + ');');
    parent.find('a.arrowUp').attr('style', 'display:' + (index == 0 ? 'none' : 'block'));
    parent.find('a.arrowDown').attr('style', 'display:' + (index == itemCount - 1 ? 'none' : 'block'));
};


/* jq helpers - TODO - to JS extensions? */
function fadeAndMove(element1, element2, index, newIndex, callback){
    element1.fadeOut(function(){
        if(index < newIndex){
            element2.after(element1);
        }else{
            element2.before(element1);
        };
        callback();
        element1.fadeIn();
    });
};


/* ## blockUI ## */

function decorateBlockedUI(){

    $.blockUI.defaults.css["border"] = '2px solid #888888';
    $.blockUI.defaults.overlayCSS["backgroundColor"] = '#606060';
    $.blockUI.defaults.overlayCSS["opacity"] = 0.6;

    $('.blockUIContainer').each(function() {
        var headerDiv = $("<div class=\"header\"></div>");
        var mlRibbonImg = $("<img class=\"mlRibbon\" src=\"" + APP_ROOT + 'client/global/img/cross-site/block_ui_header_ribbon.png' + "\"/>");
        var heading = $(this).find("h4:first");
        heading.wrap(headerDiv);
        heading.before(mlRibbonImg);
        heading.after($("<a href=\"javascript:unblockUI();\" class=\"pipeTip close\" title=\"Close|Click here to close window\"></a>"));
    });
};

function blockUI(win, dialogWidth){
    if(typeof(parent) != 'undefined' && typeof(parent.onBlockUI) == 'function'){ parent.onBlockUI(); };
    var width = $(window).width();
    dialogWidth = (typeof(dialogWidth) == 'undefined' || dialogWidth == null) ? 580 : dialogWidth;
    var xPos = ((width / 2) - (dialogWidth / 2)) + 'px';
    $.blockUI({ message: win,
                css: {
                    width: dialogWidth + 'px',
                    top: '100px',
                    left: xPos
                }
    }); 
};

function unblockUI(){
    if(typeof(parent) != 'undefined' && typeof(parent.onUnblockUI) == 'function'){ parent.onUnblockUI(); };
    $.unblockUI();
};

function getImageUri(guid, id, suffix) {
    var FORMAT = "{0}store/tributes/{1}/resources/{2}{3}.jpg?u={4}";
    var filename = '0000000000' + id;
    filename = filename.substring(filename.length, filename.length - 10);
    return doStringFormat(FORMAT, [APP_ROOT, guid, filename, suffix, new Date().getTime()]);
};

/* ## audio ## */
// func to stop audio playing in the frame - see TCSoundPlayer
function stopAudio() {
    if (typeof (parent) != 'undefined' && typeof (parent.stopAudio) == 'function') {
        parent.stopAudio();
    } else if (typeof (stopAudio) == 'function') {
        stopAudio();
    };
};


/* ## firebug ## */

// log to the firebug console
function logToFirebugConsole(v1,v2){
    if(true == IS_DEBUG){
        try {
            window.console.log(v1, typeof(v2) != 'undefined' ? v2 : "");
        }catch(e){};
    };
};


/* doc ready */
try {
    // TODO: barfing ie on admin panel state change...
    $(document).ready(function() {
        g_isBrowserWinIE = $.browser.msie;
        decorateBlockedUI();
        registerToolTips();
    });
} catch (e) { };


