﻿var EE;
if (!EE) EE = {};

function checkTALength(field, maxlen) {
    return($F(field.id).length < (maxlen));
}    

function trimTA(field, maxlen) {
    if ($F(field.id).length > maxlen) {
        alert("The text you have entered in this field is longer than the permitted " + maxlen + " characters. " +
            "The system will now automatically trim the value to the allowed length." +
            "\n\nPlease check the updated value is acceptable before proceeding.");
        $(field.id).value = $F(field.id).substring(0, maxlen);
        $(field.id).select();
        return false;
    }
    return true;
}

function validImageExtension(fileFieldName) {
    var fileName = $F(fileFieldName).toLowerCase();
    if (fileName != "" ) {
        var isJpg = (fileName.indexOf(".jpg") != -1 || fileName.indexOf(".jpeg") != -1);
        var isGif = fileName.indexOf(".gif") != -1;
        var isPng = fileName.indexOf(".png") != -1;
        
        if (!isJpg && !isGif && !isPng) {
            alert("The image you have attempted to upload is not in an acceptable format.\n\n" +
                "Please upload only JPG, GIF or PNG format files.");
            return false;
        }
    }
    return true;
}

// ---------------------------------------------------------------------------------------------

EE.AjaxHelper = {
	STATUS_SUCCESS: "SUCCESS",
	STATUS_FAILURE: "FAILURE",
	STATUS_WARNING: "WARNING"
};

EE.PagingArrows = {
    FIRST_PAGE: "<img src=\"/images/first-arrow.gif\" alt=\"First Page\">",
    PREV_PAGE: "<img src=\"/images/prev-arrow.gif\" alt=\"Prev Page\">",
    NEXT_PAGE: "<img src=\"/images/next-arrow.gif\" alt=\"Next Page\">",
    LAST_PAGE: "<img src=\"/images/last-arrow.gif\" alt=\"Last Page\">"
};

// ---------------------------------------------------------------------------------------------

EE.Core = Class.create({
    initialize: function() {
        this._displayMessageTimeMs = 9000;
    },
    
    setExt: function(ext) {
        this._ext = ext;
    },

    includeLanguageScript: function(sLangJsPath) {
        var jsfile = sLangJsPath;
        //lang variable is already set by language controller
        if (langCode == null) {
            langCode = navigator.language ? navigator.language : navigator.userLanguage;
            langCode = langCode.substr(0, 2);
        }
        switch (langCode.toLowerCase()) {
            case "en":
                jsfile += 'en.js';
                break;
            case "pl":
                jsfile += 'pl.js';
                break;
            default:
                jsfile += 'en.js';
        }
        this.require(jsfile);
    },

    /**
    * Sets every second row's class to 'even'
    */
    beautifyTable: function(oTableID) {
        var oTable = $(oTableID);
        var oTBody = oTable.getElementsBySelector('tbody').first();
        var aRows = oTBody.childElements();

        aRows.each(function(row, iIndex) {
            if (iIndex % 2) {
                row.addClassName('even')
            }
        });
    },

    /**
    * Registers AJAX loader image.
    * @param ajaxLoaderImgId ID of the AJAX loader image
    */
    registerAjaxLoader: function(ajaxLoaderImgId) {
        Ajax.Responders.register({
            onCreate: function() { Element.show(ajaxLoaderImgId) },
            onComplete: function() { Element.hide(ajaxLoaderImgId) }
        });
    },

    goToSendEmailScreen: function(sendEmailTabId, recipients) {
        tabs.setActiveTab(sendEmailTabId);
        $('to').value = recipients;
    },

    goToEventScreen: function(sendEmailTabId, orgId) {
        tabs.setActiveTab(sendEmailTabId);
        for (var i = 0; i < $(ORG_LIST_FILTER).length; i++) {
            if ($(ORG_LIST_FILTER)[i].value == orgId) {
                $(ORG_LIST_FILTER)[i].selected = true;
            }
        }
    },

    toggleSelectOptions: function(selectId, show) {
        if ($(selectId)) {
            $(selectId).childElements().each(function(item) {
                item.selected = show;
            });
        }
    },

    toggleSelectOptionsListener: function(event, selectId, show) {
        this.toggleSelectOptions(selectId, show);
        event.stop();
    },

    displayMessage: function(divId, msg, mode) {
        $(divId).update(new Element('div').update(msg));
        Effect.toggle(divId, mode);
        setTimeout("Effect.toggle('" + divId + "','" + mode + "')", this._displayMessageTimeMs);
    },

    createImage: function(sImgSrc, sImgTitle) {
        return new Element('img', { 'src': sImgSrc, 'alt': sImgTitle, 'border': '0' });
    },

    require: function(libraryName) {
        // inserting via DOM fails in Safari 2.0, so brute force approach
        document.write('<script type="text/javascript" src="' + libraryName + '"><\/script>');
    },

    getValueOfFirstParamInQueryString: function(paramName) {
        var temp = document.URL.indexOf('?' + paramName + '=');
        if (temp == -1) {
            return temp;
        }
        return document.URL.substring(temp + 2 + paramName.length);
    },
    
    openFCKEditorTooltip: function() {
      window.open("displayfckeditortooltip" + this._ext,
        "FCKEditorTooltip", "status=1, resizable=1, height=600, width=600, scrollbars=yes");
    },
    
    escapeHTMLCharacters : function(text) {
        var result = text;
        result = result.escapeHTML();
        
        // if double and single quotes haven't been 
        // escaped (i.e. you're using IE) do it now
        result = result.replace(/\'/g, "&#39;");
        result = result.replace(/\"/g, "&quot;");
        return result;
    },
    
    unescapeHTMLCharacters : function(text) {
        var result = text;
        result = result.unescapeHTML();
        
        // if double and single quotes haven't been 
        // unescaped (i.e. you're using IE) do it now
        result = result.replace(/&#39;/g, "'");
        result = result.replace(/&quot;/g, "\"");
        return result;
    },
    
    /**
     * Opens a new window with the preview.
     * @param url The URL of the action that opens the preview page.
     */
    openEventPreviewPopUp : function(url) {
        var childWindow = window.open(url, "_blank", "status=no, resizable=yes, scrollbars=yes, width=1050");

        /*
         Reload the child window to make sure that the preview page is
         up-to-date.
         Only perform this reload if IE
        */	
        if (document.all) {
            childWindow.location.reload();
        }
      	
        if (childWindow.opener == null) {
            childWindow.opener = self;
        }
    }
});

/* Cookie management functions */
function createCookie( name, value, days ) {
	if ( days ) {
		var date = new Date();
		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires +" ; path=/";
}

function readCookie( name ) {
	var nameEQ = name + "=";
	var ca = document.cookie.split( ';' );
	for( var i = 0; i < ca.length; i++ ) {
		var c = ca[i];
		while ( c.charAt( 0 ) == ' ' ) c = c.substring( 1, c.length );
		if ( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
	}
	return null;
}

function eraseCookie( name ) {
	createCookie( name, "", -1 );
}

/*
 * CSS Browser Selector v0.2.7
 * Rafael Lima (http://rafael.adm.br)
 * http://rafael.adm.br/css_browser_selector
 * License: http://creativecommons.org/licenses/by/2.5/
 * Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
var css_browser_selector = function() {
	var 
		ua = navigator.userAgent.toLowerCase(),
		is = function( t ) { return ua.indexOf( t ) != -1; },
		h = document.getElementsByTagName( 'html' )[0],
		b = ( !(/opera|webtv/i.test(ua)) && /msie (\d)/.test(ua)) ? ('ie ie' + RegExp.$1 ) : is('gecko/') ? 'gecko' : is('opera/9') ? 'opera opera9' : /opera (\d)/.test(ua) ? 'opera opera' + RegExp.$1 : is('konqueror') ? 'konqueror' : is('applewebkit/') ? 'webkit safari' : is('mozilla/') ? 'gecko':'',
		os = ( is('x11') || is('linux') ) ? ' linux' : is('mac') ? ' mac' : is('win') ? ' win':'';
	var c = b + os + ' js';
	h.className += h.className ? ' ' + c : c;
}();

/**
 * Add some useful methods to string objects.
 */
Object.extend(String.prototype, {
    isNumber: function() {
        return !this.blank() && /^\d+$/.test(this);
    },

    isFloat: function() {
        return !this.blank() && /^\d*(\.\d{1,2})?$/.test(this);
    },

    isDate: function() {
        return /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(this);
    },

    isEmail: function() {
        return /^\w+(\.\w+)*@(\w+\.)+\w{2,5}$/.test(this);
    }
});

preventValidDecimal = function(event) {
    var k = event.keyCode ? event.keyCode : event.charCode ? event.charCode : event.which;
    // special characters (backspace, arrows, etc.) should be allowed
    if (k == 8 || k == 9 || k == 13 || k == 16 || k == 17 || k == 20 || 
        k == 35 || k == 36 || k == 37 || k == 38 || k == 39 || 
        k == 40 || k == 46 || k == 58) {
        return true;
    }
    var currentValue = $F('booking_PaymentTotal');
    var dotIndex = currentValue.indexOf('.');
    if (dotIndex != -1) {
        // if there was decimal separator (.) another one is prohibited
        if (String.fromCharCode(k) == '.')
            return false;
        // if two decimal chars are already in place, do not allow another one        
        if (currentValue.substring(dotIndex + 1).length >= 2) 
            return false;
    }
    //finally, check if user pressed 0-9 or dot
    return /^[0-9\.]$/.test(String.fromCharCode(k));
}
