/* NEEDED FOR IMPORTING OTHER SCRIPTS */
var getLauObj = function(){
	if(typeof(XMLHttpRequest)!='undefined')
		return new XMLHttpRequest();
	var axO=['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.4.0',
		'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'], i;
	for(i=0;i<axO.length;i++)
		try{
			return new ActiveXObject(axO[i]);
		}catch(e){}
	return;
}
var loadLauScript = function(scriptpath, functions){
	var oXML = getLauObj();
	oXML.open('GET', scriptpath, false);
	oXML.send('');
	eval(oXML.responseText);
	for(var i=0; i<functions.length; i++)
		window[functions[i]] = eval(functions[i]);
}

/* INITIALIZE THE LAU FORM FRAMEWORK */
var initLauForms = function(options) {
    var options = jQuery.extend({
        theme:          'default',
        formClass:      'form.lau-form',
        urlPart1:       '/ajax/',
        urlPart2:       '_interface.php?p_id=',
        geoply_url:     '/Admin/Moderators/geoply_proxy.php?p_id=',
        jsBase:         'js/',
        cssBase:        'css/',
        dateMinus:      '10',
        datePlus:       '0',
        fieldSettings:  {
            location: {
                useCrumbs:  true,
                useCounts:  true
            },
            geoply: {
                useCrumbs:  true,
                useCounts:  true
            },
            job_cat: {
                useCrumbs:  true,
                useCounts:  true
            }
        }
    }, options);
    // We can now set-up the global variables...
    lauTheme = options.theme;
    lauClass = options.formClass;
    urlPart1 = options.urlPart1;
    urlPart2 = options.urlPart2;
    lauSettings = options.fieldSettings;
    geoply_url = options.geoply_url;
    js_base = options.jsBase;
    css_base = options.cssBase;
    datepicker_minus = options.dateMinus;
    datepicker_plus = options.datePlus;
    if(css_base!='css/'){
        //$('head').appendTo('<link type="text/css" href="'+css_base+'forms.css" media="screen" rel="stylesheet" />');
    }
    /* LOAD COMMON FORM SCRIPTS */
    var commonFunctions = ['checkString', 'lauCountProperties', 'jQuery.fn.positionAncestor'];
    loadLauScript(js_base+'forms.common.js',commonFunctions);
    /*
     *  Please note that form elements must use the class "lau-form"...
     *
     *  First need to perform basic tasks,
     *  such as wrapping forms, inputs and areas...
     *
     */
    $(lauClass).addClass(lauTheme);
    var hr = '<span class="hr"></span>';
    var wrap; var wrapHalf;
    var wrapHalfright;var wrapThirds;
    var wrapThirdsMiddle;var wrapThirdsRight;
    $(lauClass).find('hr').each(function() {
        var hrClass = $(this).attr('class');
        var tempHRid = $(this).attr('id');
        if(tempHRid != '') {
            var hrIDarray = $(this).attr('id').split('--');
            var hrID = hrIDarray[0];
        }else{
            var hrID = '';
        }
        $(this).after(hr);
        wrap = '<div class="form-wrapper" id="form-wrapper-'+hrID+'"/>';
        wrapHalf = '<div class="form-wrapper style-half" id="form-wrapper-'+hrID+'"/>';
        wrapHalfright = '<div class="form-wrapper style-half right" id="form-wrapper-'+hrID+'"/>';
        wrapThirds = '<div class="form-wrapper style-thirds" id="form-wrapper-'+hrID+'"/>';
        wrapThirdsMiddle = '<div class="form-wrapper style-thirds middle" id="form-wrapper-'+hrID+'"/>';
        wrapThirdsRight = '<div class="form-wrapper style-thirds right" id="form-wrapper-'+hrID+'"/>';
        if(hrClass=='half right') {var thisWrap = wrapHalfright;}
        else if(hrClass=='half') {var thisWrap = wrapHalf;}
        else if(hrClass=='thirds') {var thisWrap = wrapThirds;}
        else if(hrClass=='thirds middle') {var thisWrap = wrapThirdsMiddle;}
        else if(hrClass=='thirds right') {var thisWrap = wrapThirdsRight;}
        else{var thisWrap = wrap;}
        $(this).add($(this).nextUntil('hr')).wrapAll(thisWrap);
        $(this).remove();
    });
    $(lauClass).after(hr);
    $(lauClass).find('div.lau-expand').each(function() {
        var expandedState = $(this).attr('class');
        var thisTitleArray = $(this).attr('title').split(',');
        var thisTitle = thisTitleArray[0]; var thisClosedText = thisTitleArray[1]; var thisOpenedText = thisTitleArray[2];
        if(expandedState=='lau-expand'){ $(this).addClass('close'); }
        $(this).before('<a href="#" id="'+$(this).attr('id')+'-link" class="lau-expand-link">'+thisTitle+'<span class="expand-label" id="'+$(this).attr('id')+'-expand-label" rel="'+thisOpenedText+'">'+thisClosedText+'</span></a>')
    });
    $(lauClass).find('input.lau-text').each(function() {
        $(this).focus(function() {
            $(this).addClass('lau-focus');
            $(this).blur(function() {
                $(this).removeClass('lau-focus');
            });
        });
    });
    /*
    $(lauClass).find('textarea.lau-area').each(function() {
        $(this).focus(function() {
            $(this).addClass('lau-focus');
            $(this).blur(function() {
                $(this).removeClass('lau-focus');
            });
        });
    });
    */
    $('.ui-datepicker-trigger').live('mouseover', function() {
        $(this).prev().addClass('selected');
    });
    $('.ui-datepicker-trigger').live('mouseout', function() {
        $(this).prev().removeClass('selected');
    });
    $('.lau-expand-link').live('click', function(e) {
        e.preventDefault();
        var thisIDarray = $(this).attr('id').split('-');
        var thisID = thisIDarray[0];
        var thisDiv = $('div#'+thisID);
        var thisSpan = $('span#'+thisID+'-expand-label');
        var expandedState = $(thisDiv).attr('class');
        if(checkString(expandedState,'open')){
            $(thisDiv).removeClass('open');
            $(thisDiv).addClass('close');
            var tempHTML = $(thisSpan).html();
            $(thisSpan).html($(thisSpan).attr('rel'));
            $(thisSpan).attr('rel', tempHTML);
        }else{
            $(thisDiv).removeClass('close');
            $(thisDiv).addClass('open');
            var tempHTML = $(thisSpan).html();
            $(thisSpan).html($(thisSpan).attr('rel'));
            $(thisSpan).attr('rel', tempHTML);
        }
    });
    resizeLauForms();
    /*
     *  AJAX DROP DOWN MENU
     *
     *  This function requires an input text with an associated label.
     *  The ID for the input must contain a key and the AJAX type,
     *  where the associated ID is obtained by the default valuea.
     *
     *  The input must also be given the "ajax-dd" class...
     *
     *  At present, the following AJAX Types are supported:
     *
     *  --> locations
     *
     *  Example code:
     *
     *  <label for="key1-location">Select Location:</label>
     *  <input id="key1-location" type="text" class="ajax-dd" value="0" autocomplete="off">
     *
     */
    var ajax_dd = [];
        // Set-up the ajax_dd array...
        ajax_dd.selector = lauClass+' input.ajax-dd';
        $(ajax_dd.selector).each(function() {
            // Only include required functions IF using the AJAX DD
            var ajaxDDoptions = ['initAjaxDD', 'replaceInputsAjaxDD', 'ajaxListDD', 'ajaxGetDD', 'ajaxUpdateDD', 'ajaxDDreset', 'toggleDD', 'resizeAjaxDD', 'resizeAjaxDDheight'];
            if(window.initAjaxDD) { /* Function already loaded */ }else{loadLauScript(js_base+'forms.ajaxdd.js',ajaxDDoptions);}
            // Gather Information
            ajax_dd.input = $(this);
            ajax_dd.inputID = $(this).attr('id');
            ajax_dd.name = $(this).attr('name');
            ajax_dd.idArray = $(this).val().split(',');
            ajax_dd.inputArray = ajax_dd.inputID.split('-');
            ajax_dd.key = ajax_dd.inputArray[0];
            ajax_dd.ajaxType = ajax_dd.inputArray[1];
            ajax_dd.label = $('label[for='+ajax_dd.inputID+']');
            ajax_dd.title = $(ajax_dd.label).html();
            ajax_dd.id = '';$.each(ajax_dd.idArray, function(index, value) {if(ajax_dd.id == '') {ajax_dd.id=value;}else{ajax_dd.id+='-'+value;}});
            if(ajax_dd.idArray.length > 1){ajax_dd.isArray = 1;}else{ajax_dd.isArray = 0;}
            // Replace existing elements with AJAX drop-down elements
            replaceInputsAjaxDD(ajax_dd);
            // Initialise AJAX Lists
            initAjaxDD(ajax_dd);
        });
    // End of AJAX DROP DOWN MENU

    /* GEOPLY DROP-DOWN */
    var geoply_dd = [];
        // Set-up the ajax_dd array...
        geoply_dd.selector = lauClass+' input.geoply-dd';
        $(geoply_dd.selector).each(function() {
            // Only include required functions IF using the AJAX DD
            var geoplyDDoptions = ['initGeoplyDD', 'replaceInputsGeoplyDD', 'geoplyListDD', 'geoplyGetDD', 'geoplyUpdateDD', 'geoplyDDreset', 'toggleGeoplyDD', 'geoply_resize_sidebar', 'resizeGeoplyDD', 'resizeGeoplyDDheight'];
            if(window.initGeoplyDD) { /* Function already loaded */ }else{loadLauScript(js_base+'forms.geoplydd.js',geoplyDDoptions);}
            // Gather Information
            geoply_dd.input = $(this);
            geoply_dd.inputID = $(this).attr('id');
            geoply_dd.name = $(this).attr('name');
            geoply_dd.idArray = $(this).val().split(',');
            geoply_dd.key = $(this).attr('data-key');
            geoply_dd.ajaxType = $(this).attr('data-ajaxType');
            geoply_dd.displayMap = $(this).attr('data-displayMap');
            geoply_dd.displaySidebar = $(this).attr('data-displaySidebar');
            geoply_dd.adminMode = $(this).attr('data-adminMode');
            geoply_dd.label = $('label[for='+geoply_dd.inputID+']');
            geoply_dd.title = $(geoply_dd.label).html();
            geoply_dd.id = '';$.each(geoply_dd.idArray, function(index, value) {if(geoply_dd.id == '') {geoply_dd.id=value;}else{geoply_dd.id+='-'+value;}});
            if(geoply_dd.idArray.length > 1){geoply_dd.isArray = 1;}else{geoply_dd.isArray = 0;}
            // Replace existing elements with AJAX drop-down elements
            replaceInputsGeoplyDD(geoply_dd);
            // Initialise AJAX Lists
            initGeoplyDD(geoply_dd);
        });
    // End of GEOPLY DROP DOWN MENU

    /*
     *  LAU DROP-DOWN
     *
     *  This function requires a select tag with an associated label.
     *  
     *  The input must also be given the "lau-dd" class...
     *
     *  Example code:
     *
     *  
     *
     */
    var lau_dd = [];
        // Set-up the ajax_dd array...
        lau_dd.selector = lauClass+' select.lau-dd';
        $(lau_dd.selector).each(function() {
            // Only include required functions IF using the LAU DD
            var lauDDoptions = ['initLauDD','replaceInputsLauDD','updateLauDD','updateLauDDvalue','toggleLauDD','resizeLauDD','resizeLauDDheight'];
            if(window.initLauDD) { /* Function already loaded */ }else{loadLauScript(js_base+'forms.laudd.js',lauDDoptions);}
            // Gather Information
            lau_dd.select = $(this);
            lau_dd.selectID = $(this).attr('id');
            lau_dd.label = $('label[for='+lau_dd.selectID+']');
            lau_dd.name = $(this).attr('name');
            lau_dd.originalID = $(this).attr('id');
            $(this).attr('id','select-'+lau_dd.originalID);
            lau_dd.title = $(lau_dd.label).html();
            // Replace existing elements with Lau Drop-Down elements
            replaceInputsLauDD(lau_dd.selectID, lau_dd.title, lau_dd.name);
            // Initialise AJAX Lists
            initLauDD(lau_dd);
        });
    // End of Standard Drop Down
    resizeLauForms();
    /*
     *  LAU DATE-PICKER
     *
     *  This function requires a select tag with an associated label.
     *
     *  The input must also be given the "lau-dd" class...
     *
     *  Example code:
     *
     *
     *
     */
    var lau_date = [];
        // Set-up the ajax_dd array...
        lau_date.selector = lauClass+' input.lau-date';
        $(lau_date.selector).each(function() {
            var lauDateOptions = ['initLauDate','getDateSuffix','getPrettyDate','resizeLauDate'];
            if(window.initLauDate) { /* Function already loaded */ }else{loadLauScript(js_base+'forms.laudate.js',lauDateOptions);}
            // Gather information
            lau_date.input = $(this);
            lau_date.inputID = $(this).attr('id');
            // Initialise date-picker
            initLauDate(lau_date.inputID);
        });
    // End of date-picker

    /*
     *  WYSIWYG EDITOR
     *
     *  In order to add WYSIWYG editing capability to a textarea, simply
     *  add an additional class called "wysiwyg"
     *
     *  Example code:
     *
     *
     *
     */
    var lau_wysiwyg = [];
        $(lauClass).find('textarea.lau-area.wysiwyg').each(function() {
            //var lauWYSIWYGfunctions = [''];
            if(window.Wysiwyg) { /* Function already loaded */ }else{loadLauScript(js_base+'jquery.wysiwyg.js','');}
            var thisID = $(this).attr('id');
            $('#'+thisID).wysiwyg({
               css: '/css/ll/forms.css',
               controls: {
                   strikeThrough: { visible: false },
                   subscript: { visible: false },
                   superscript: { visible: false },
                   undo: { visible: false },
                   redo: { visible: false },
                   insertImage: { visible: false },
                   insertHorizontalRule: { visible: false },
                   h1mozilla: { visible: false },
                   h2mozilla: { visible: false },
                   h3mozilla: { visible: false },
                   h1: { visible: false },
                   h2: { visible: false },
                   h3: { visible: false },
                   cut: { visible: false },
                   copy: { visible: false },
                   paste: { visible: false },
                   increaseFontSize: { visible: false },
                   decreaseFontSize: { visible: false },
                   html: { visible: false },
                   removeFormat: { visible: false },
                   insertTable: { visible: false }
               },
               events: {
                   focus: function() {
                       $('#form-wrapper-'+thisID).find('div.wysiwyg').addClass('lau-focus');
                   },
                   blur: function() {
                       $('#form-wrapper-'+thisID).find('div.wysiwyg').removeClass('lau-focus');
                   }
               },
               initialContent: $(this).html()
            });
        });
    // End of WYSIWYG Editor

    /*
     *  LAU RADIO
     *
     *  This function requires a input type="radio" and class="lau-radio"
     *
     *  It is also essential for each input to have an ID relevant to the label
     *  and <hr> whilst adcding sequential numbers to each unique radio input
     *  from within that particular set of radio inputs
     *
     *  Example code:
     *
     *
     *
     */
    var lau_radio = [];
        // Set-up the ajax_dd array...
        lau_radio.selector = lauClass+' input.lau-radio';
        $(lau_radio.selector).each(function(index) {
            // Only include required functions IF using the LAU RADIO
            var lauRadioFunctions = ['replaceLauRadio','toggleLauRadio'];
            if(window.replaceLauRadio) { /* Function already loaded */ }else{loadLauScript(js_base+'forms.lauradio.js',lauRadioFunctions);}
            // Gather Information
            lau_radio.radio = $(this);
            lau_radio.radioIDarray = $(this).attr('id').split('-');
            lau_radio.radioIDset = lau_radio.radioIDarray[0];
            lau_radio.radioID = lau_radio.radioIDarray[1];
            lau_radio.checked = $(this).attr('checked');
            var thisHTML = $('div#form-wrapper-'+lau_radio.radioIDset).html();
            var thisValue;
            $(this).next().addClass('radio-label').attr('id', lau_radio.radioIDset+'-'+lau_radio.radioID+'-radio-label');
            if(lau_radio.checked){ 
                $(this).next().addClass('checked');
                thisValue = $(this).val();
                $('input#lau-radio-value-'+lau_radio.radioIDset).val(thisValue);
            }
            if(checkString(thisHTML,'lau-radio-value-'+lau_radio.radioIDset)){ /* DO NOTHING */ }else{
                $('div#form-wrapper-'+lau_radio.radioIDset).append('<input id="lau-radio-value-'+lau_radio.radioIDset+'" type="hidden" name="'+$(this).attr('name')+'"'+thisValue+'>');
            }
            replaceLauRadio(lau_radio.radioIDset, lau_radio.radioID);
        });
    // End of Lau Radio

    /*
     *  LAU CHECKBOX
     *
     *  This function requires a input type="checkbox" and class="lau-check"
     *
     *  It is also essential for each input to have an ID relevant to the label
     *  and <hr> whilst adding sequential numbers to each unique radio input
     *  from within that particular set of checkbox inputs
     *
     *  Example code:
     *
     *
     *
     */
    var lau_check = [];
        // Set-up the ajax_dd array...
        lau_check.selector = lauClass+' input.lau-check';
        $(lau_check.selector).each(function(index) {
            // Only include required functions IF using the LAU RADIO
            var lauCheckFunctions = ['replaceLauCheck','toggleLauCheck'];
            if(window.replaceLauCheck) { /* Function already loaded */ }else{loadLauScript(js_base+'forms.laucheck.js',lauCheckFunctions);}
            // Gather Information
            lau_check.check = $(this);
            lau_check.checkIDarray = $(this).attr('id').split('-');
            lau_check.checkIDset = lau_check.checkIDarray[0];
            lau_check.checkID = lau_check.checkIDarray[1];
            lau_check.checked = $(this).attr('checked');
            var thisHTML = $('div#form-wrapper-'+lau_check.checkIDset).html();
            var thisValue;
            $(this).next().addClass('check-label').attr('id', lau_check.checkIDset+'-'+lau_check.checkID+'-check-label');
            if(lau_check.checked){
                $(this).next().addClass('checked');
                thisValue = $(this).val();
                $('div#form-wrapper-'+lau_check.checkIDset).append('<input id="lau-check-value-'+lau_check.checkIDset+'-'+lau_check.checkID+'" type="hidden" name="'+lau_check.checkIDset+'[]" value="'+thisValue+'">');
            }
            replaceLauCheck(lau_check.checkIDset, lau_check.checkID);
        });

    // End of ALL form functionality - time to style things...
    resizeLauForms();

    /* These trigger the appropriate resize functions */
    $('.form-wrapper').bind('resize', function() {
        resizeLauForms();
    });
    $(window).bind('resize', function() {
        if($.browser.msie){
            resizeLauForms();
        }
    });
    $(window).resize(function() {
        var screenHeight = $(window).height();
        $(lauClass).find('.form-wrapper').each(function() {
            if(window.initAjaxDD) {
                resizeAjaxDDheight($(this), screenHeight);
            }
            if(window.initGeoplyDD) {
                resizeGeoplyDDheight($(this), screenHeight);
            }
            if(window.initLauDD) {
                resizeLauDDheight($(this), screenHeight);
            }
        });
    });
    
}

var resizeLauFormBasics = function(wrapper, screenHeight, formWidth) {
    $(wrapper).find('input.lau-text').each(function() {
        $(this).width(formWidth);
        var widthDiff = $(this).outerWidth() - formWidth;
        /* UNEXPLAINABLE NEED */
        if(widthDiff>0){
            $(this).width($(this).width()-widthDiff)
        }
    });
    $(wrapper).find('textarea.lau-area').each(function() {
        $(this).width(formWidth);
        var widthDiff = $(this).outerWidth() - formWidth;
        /* UNEXPLAINABLE NEED */
        if(widthDiff>0){
            $(this).width($(this).width()-widthDiff)
        }
    });
    $(wrapper).find('a.lau-expand-link').each(function() {
        $(this).width(formWidth);
        var widthDiff = $(this).outerWidth() - formWidth;
        /* UNEXPLAINABLE NEED */
        if(widthDiff>0){
            $(this).width($(this).width()-widthDiff)
        }
    });
}

var resizeLauForms = function() {
    var screenHeight = $(window).height();
    $(lauClass).find('.form-wrapper').each(function() {
        var formWidth = $(this).width();
        //$(this).width(formWidth);
        resizeLauFormBasics($(this), screenHeight, formWidth);
        if(window.initAjaxDD) {
            resizeAjaxDD($(this), screenHeight, formWidth);
        }
        if(window.initGeoplyDD) {
            resizeGeoplyDD($(this), screenHeight, formWidth);
        }
        if(window.initLauDD) {
            resizeLauDD($(this), screenHeight, formWidth);
        }
        if(window.initLauDate) {
            resizeLauDate($(this), formWidth);
        }
        var frameDiff = 31;
        var panelDiff = 21;
        if($.browser.msie) { frameDiff = 44; panelDiff = 3; }
        $(this).find('div.wysiwyg').width(formWidth-1);
        $(this).find('div.wysiwyg ul.panel').width(formWidth-panelDiff);
        $(this).find('.lauFrame').width(formWidth-frameDiff);
    });
}
