function $() {
    var elements = new Array();
    
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        
        if (arguments.length == 1)
            return element;
        
        elements.push(element);
    }
    
    return elements;
}

function obi(){
    var elements = new Array();
    
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        
        if (arguments.length == 1)
            return element;
        
        elements.push(element);
    }
    
    return elements;
}

var loading = true;
//function to replace an image with a standard on if the one looking for doesn't exist
function noImg(objectID, imgToUseIfError){
    document.getElementById(objectID).innerHTML='<img src="' + imgToUseIfError + '">';
}

function lib_bwcheck(){
    this.ver=navigator.appVersion;
    this.agent=navigator.userAgent;
    this.dom=document.getElementById?1:0;
    this.opera5=this.agent.indexOf("Opera 5")>-1;
    this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
    this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
    this.ie7=(this.ver.indexOf("MSIE 7")>-1 && this.dom && !this.opera5)?1:0;
    this.ie8=(this.ver.indexOf("MSIE 8")>-1 && this.dom && !this.opera5)?1:0;
    this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
    this.ie=this.ie4||this.ie5||this.ie6;
    this.mac=this.agent.indexOf("Mac")>-1;
    this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
    this.ns4=(document.layers && !this.dom)?1:0;
    this.bw=(this.ie8 || this.ie7 || this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5);
    return this;
}
var bw=new lib_bwcheck();
/***************************************************************************************
 Variables to set:
 ***************************************************************************************/
var validation;

fromX = 5;
fromY = -20;

//Makes crossbrowser object.
function makeObj(obj){
    this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
    if(!this.evnt) return false
    this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
    this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
    this.writeIt=b_writeIt;
    return this
}
/************************************************
 Multilingual javascript triggered errors
 ************************************************/
// Creates and populates object containing english error messages - runs on load
var errorMessages = new Object();
errorMessages.exactDiff = "Unable to calculate the exact difference.";
errorMessages.sorryNoMatch = "Sorry, no matching items found.";
errorMessages.noMatchTryAagin = "Sorry, no matching items found. Please try another postcode.";
errorMessages.cantObtainAddDetails = "Unable to obtain address details. Please try again.";
errorMessages.needsValidReg = "Please enter a valid registration number.";
errorMessages.tobAgree = "You must agree to our Terms of Business before proceeding.";
// currently send direct by postcode anywhere service so cannot be overridden
// todo when we have less time - duplicate the validation on the postcode and raise error via ebroker
errorMessages.completePostCode = "Please supply a complete postcode.";
errorMessages.pcaBadAccount = "Sorry there is a problem with our postcode service, please contact us direct.";


// A unit of measure that will be added when setting the position of a layer.
var px = bw.ns4||window.opera?"":"px";

function b_writeIt(text){
    if (bw.ns4){this.wref.write(text);this.wref.close()}
    else this.wref.innerHTML = text
}

//Capturing mousemove
var descx = 0
var descy = 0
function popmousemove(e){
    descx=bw.ns4||bw.ns6?e.pageX:event.x; 
    descy=bw.ns4||bw.ns6?e.pageY:event.y;
}


var oDesc;
//Shows the help
function showHelp(helpTitle, helpText, objImage) {
    if(typeof(_noTitles)!="undefined" && _noTitles!=null){
        var message = '<div class="clHeading"><b> Help</b></div>' + helpText + '</div>';
    }
    else{
        var message = '<div class="clHeading"><b> Help</b></div><b>' + helpTitle +
        ':</b><br>' + helpText + '</div>';
    }
    if(oDesc){
        oDesc.writeIt('<div class="clHelp">'+message+'</div>')
        if(bw.ie5||bw.ie6||bw.ie7||bw.ie8) {
            //descy = descy + document.body.scrollTop
            var element = objImage;
            var x = 0;
            while (element) {
                if (element.offsetParent) {
                    x += element.offsetLeft;
                } else if (element.x) {
                    x += element.x;
                }
                element = element.offsetParent;
            }
            descx += x;
            
            element = objImage;
            var y = 0;
            descy = 0;
            while (element) {
                if (element.offsetParent) {
                    y += element.offsetTop;
                } else if (element.y) {
                    y += element.y;
                }
                element = element.offsetParent;
                
            }
            descy += y;
        }else{ 
            descy += 10;
        }
        
        oDesc.css.left = (descx+fromX)+px;
        oDesc.css.top = (descy+fromY)+px;
        oDesc.css.visibility = "visible";
        //oDesc.css.z-index = 2
    }
}

function hideHelp(){
    if(oDesc) oDesc.css.visibility = "hidden"
    
}

function initHelp(){
    if(bw.ns4)document.captureEvents(Event.MOUSEMOVE)
    document.onmousemove = popmousemove;
    oDesc = new makeObj('divDescription')
}

function focusFirst(){
    var fields = document.getElementById('form1').getElementsByTagName('*');
    for(var ii = 0; ii < fields.length; ii++){
        switch(fields[ii].tagName.toLowerCase()){
            case 'input':
            case 'select':
                if(fields[ii].disabled == false && fields[ii].id != 'form1:lstAddresses' && fields[ii].type != 'hidden'){
                    try{
                        fields[ii].focus();
                    }catch(e){
                        //Do nothing
                    }
                    return;
                }
                break;
        }
    }
}

function copyFields(sFrom, sTo){
    try{
        var aFrom = sFrom.split(',');
        var aTo = sTo.split(',');
        
        for(var ii = 0; ii < aFrom.length; ii++){
            document.getElementById(aTo[ii]).value = document.getElementById(aFrom[ii]).value;
        }
    }catch(ex){}
}

var nextClicked = false;
function clickOnce() {
    try {
        if (nextClicked) {
            return false;
        } else {
            nextClicked = true;
            return true;
        } 
    } catch (ex) {
        return false;
    }
}

function dateDiff(fromDate,toDate){
    if(fromDate != '' && toDate != ''){
        var tempDate = new Date();
        if(fromDate.getTime() > toDate.getTime()){
            tempDate = new Date(fromDate);
            fromDate = new Date(toDate);
            toDate = new Date(tempDate);
        }
        
        var fromYear = fromDate.getFullYear();
        var fromMonth = fromDate.getMonth();
        var fromDay = fromDate.getDate();
        var toYear = toDate.getFullYear();
        var toMonths = toDate.getMonth();
        var toDay = toDate.getDate();
        
        fromDate.setHours(00,00,00,00);
        toDate.setHours(00,00,00,00);
        
        var totDays = Math.ceil((toDate.getTime() - fromDate.getTime()) / 864e5);
        
        var years = toYear - fromYear;
        
        var months = 0;
        if(toMonths >= fromMonth){
            months = toMonths - fromMonth;
        }else{
            months = (11 - fromMonth) + toMonths;
            if(years > 0){years -= 1}
        }
        
        var days = 0;
        if(toDay >= fromDay){
            days = toDay - fromDay;
        }else{
            days = (31 - fromDay) + toDay;
            if(months > 0){
                months -= 1;
            }else if(months == 0){
                if(years > 0){
                    years -= 1;
                    months = 11;
                }
            }
        }
        
        calcDate = dmyAdd(fromDate,days,months,years);
        
        var adjDays = 0;
        var loopCount = 0;
        var daysInMonthDate = new Date();
        var daysInMonth = 0;
        if(calcDate.getTime() != toDate.getTime()){
            do{
                adjDays = Math.ceil((toDate.getTime() - calcDate.getTime()) / 864e5);
                days = days + adjDays;
                if(days < 0){
                    if(months > 0){months -= 1}
                    days = days + toDay;
                }
                
                daysInMonthDate = new Date(toDate);
                daysInMonth = getDaysInMonth(daysInMonthDate);
                if(days > daysInMonth){
                    daysInMonthDate.setMonth(daysInMonthDate.getMonth() - 1);
                    daysInMonth = getDaysInMonth(daysInMonthDate);
                    months += 1;
                    if(months == 12){years += 1; months = 0}
                    days -= daysInMonth;
                }
                
                calcDate = dmyAdd(fromDate,days,months,years);
                loopCount += 1;
            }while((calcDate.getTime() != toDate.getTime()) && loopCount < 4)
                if(loopCount == 4 || days < 0){alert(errorMessages.exactDiff)};
        }
        
        this.years = years;
        this.months = months;
        this.days = days;
        
        var totMonths = (years * 12) + months;
        this.totMonths = totMonths;
        
        var roundMonths = 0;
        if(days >= 15){roundMonths = months + 1}else{roundMonths = months}
        this.roundMonths = roundMonths;
        
        var totRoundMonths = (years * 12) + roundMonths;
        this.totRoundMonths = totRoundMonths;
        
        var weeks = 0;
        if(days >= 7){weeks = Math.floor(days / 7)}
        this.weeks = weeks;
        
        var weekDays = 0;
        if(weeks > 0){weekDays = days - (weeks * 7)}else{weekDays = days}
        this.weekDays = weekDays;
        
        this.totDays = totDays;
        
        var textDays = '';
        if(years){textDays += years + ((years == 1) ? ' year, ' : ' years, ')}
        if(months){textDays += months + ((months == 1) ? ' month, ' : ' months, ')}
        if(weeks){textDays += weeks + ((weeks == 1) ? ' week, ' : ' weeks, ')}
        if(weekDays){textDays += weekDays + ((weekDays == 1) ? ' day ' : ' days ')}
        
        if(textDays.charAt(textDays.length - 2) == ','){textDays = textDays.substring(0, textDays.length - 2)}
        
        this.textDays = textDays;
        
        
        //alert('years = '+years+'\nmonths = '+months+'\ndays = '+days+'\ntotMonths = '+totMonths+'\ntotRoundMonths = '+totRoundMonths+'\nroundMonths = '+roundMonths+'\nweeks = '+weeks+'\nweekDays = '+weekDays+'\ntotDays = '+totDays+'\nfromDate = '+fromDate+'\ntoDate = '+toDate+'\ncalcDate = '+calcDate+'\nadjDays = '+adjDays);
        //alert(textDays);
        
    }else{
        this.years = '';
        this.months = '';
        this.days = '';
        this.totMonths = '';
        this.roundMonths = '';
        this.totRoundMonths = '';
        this.weeks = '';
        this.weekDays = '';
        this.totDays = '';
        this.textDays = '';
    }
}

function makeDateTime(dateTime){
    if(dateTime){
        var dateTimeValues = dateTime.split(/\D+/);
        
        this.years = dateTimeValues[2];
        this.months = padNumber(parseInt(dateTimeValues[1]-1),2);
        this.days = dateTimeValues[0];
        this.hours = (dateTimeValues[3]) ? dateTimeValues[3] : 00;
        this.minutes = (dateTimeValues[4]) ? dateTimeValues[4] : '00';
        this.seconds = (dateTimeValues[5]) ? dateTimeValues[5] : '00';
        this.milliseconds = (dateTimeValues[6]) ? dateTimeValues[6] : '00';
        
        return new Date(this.years,this.months,this.days,this.hours,this.minutes,this.seconds,this.milliseconds);
    }else{
        return '';
    }
}

function padNumber(number,padding){
    while(String(number).length < padding){
        number = '0' + number;
    }
    
    return number;
}

function dmyAdd(dateTime,days,months,years){
    if(dateTime){
        var targetDate = new Date(dateTime);
        
        years = parseInt(years);
        months = parseInt(months);
        days = parseInt(days);
        
        if(! years == 0){targetDate.setFullYear(targetDate.getFullYear() + years)}
        if(! months == 0){targetDate.setMonth(targetDate.getMonth() + months)}
        if(! days == 0){targetDate.setDate(targetDate.getDate() + days)}
        
        return targetDate;
    }else{
        return '';
    }
}

function getDaysInMonth(dateTime){
    var tmpDate, d, m;
    if(dateTime){
        tmpDate = new Date(dateTime);
        m = tmpDate.getMonth();
        d = 28;
        do{
            d++;
            tmpDate.setDate(d);
        }while(tmpDate.getMonth() == m);
        
        return d - 1;
    }else{
        return '';
    }
}


//Custom Event object for making event attachment
var Event = {
    
    attach : function(obj, sEvt, func, context) {
        var newFunc = OGIFunction.bindContext(func, (context || obj));
        if (obj.addEventListener) {
            //Assumes FF
            obj.addEventListener(sEvt, newFunc, false);
        } else {
            //Assumes IE
            obj.attachEvent("on" + sEvt, newFunc);
        }
    }
    
};

//Custom Function object for binding context to a function call
var OGIFunction = {
    
    bindContext : function(func, context) {
        var proxy = function() {
            func.call(context);
        }
        
        return proxy;
    }
    
};

