if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

(function(){
    var scrollTo = !!window.scrollTo;
    var scroll = !!window.scroll;
    
    var o = null;
    var win = true;
    
    if(scrollTo == true){
        o = window.scrollTo;
    }else if(scroll == true){
        o = window.scroll;
    }else{
        o = function(){};
        win = false;
    }
    
    /**
     * Extends window.scroll(To) to accept and object with x/y or top/left properties or an id of a document element
     */
    var s = function _scrollTo(){
        if((arguments.length > 0) && (win)){
            /*var Cx = settings.scrollPositionInterface.getScrollX();
            var Cy = settings.scrollPositionInterface.getScrollY();*/
        
            var obZero = arguments[0];
            
            if(typeof obZero == 'string'){
                s($('#' + obZero).offset());
            }else if(typeof obZero == 'object'){
                if(!!obZero.x){
                    o(obZero.x, obZero.y);
                }else if(!!obZero.X){
                    o(obZero.X, obZero.Y);
                }else if(!!obZero.top){
                    o(obZero.top, obZero.left);
                }
            }else if((typeof obZero == 'number')){
                /*if(arguments.length == 1){
                    o(Cx, obZero);            
                }else if(obZero == -1){
                    o(obZero, Cy);            
                }else{
                    o(obZero, arguments[1]);            
                }*/
                o(obZero, arguments[1]);
            }
        }else if(win){
            o(0,0);
        }
        return win;
    }
    
    window.scroll = s;
    window.scrollTo = s;
    
    window.scrollTop = function(){o(0,0);return win;}
})();

var $php = new PHP_JS();
var $cRoot = null;

function preLoadImages(imgs){
    var images = null;
    if(arguments.length > 0){
        images = Array.prototype.slice.call(arguments);
    }else if(typeof imgs == "string"){
        images = new Array(imgs);
    }else{
        images = imgs;
    }
    
    if((!!document.images) && ((!!images) && ((!!images.length) && (images.length > 0)))){
        var preload_image_object = new Image();
        var i = 0;
        var c = images.length;
        for(i=0; i<c; i++){
            try{
                preload_image_object.src = images[i];
            }catch(e){}
        }
    }
}

function sendForm(event,form,to){
    event.preventDefault();
    var tis = $(form);
    
    tis.find('input, textarea').attr("disabled","disabled");
    
    var button  = tis.find('input[name="SendButton"]');
    button.val("Sending");
    
    var nme = tis.find('input[name="NME"]').val();
    var add = tis.find('input[name="FRM"]').val();
    var msg = tis.find('textarea[name="MSG"]').val();
    var sco = tis.find('input[name="securitycode"]').val();
    var mch = tis.find('input[name="matchthis"]').val();
    var cpy = tis.find('input[name="METO"]').is(':checked') ? 'checked' : '';
    
    var pdata = {
        NME:nme,
        FRM:add,
        MSG:msg,
        METO:cpy,
        securitycode:sco,
        matchthis:mch,
        Request:to,
        ajax:true
    };
    
    $.post('contactForm/sendMail.php?send',pdata,function(data,textstatus,jhxr){
        alert(data);
        button.val("Sent");
    })
    .fail(function(jqhxr){
        alert("An error occured sending you email:\n" + jqhxr.responseText);  
        button.val("Send");
        tis.find('input, textarea').removeAttr("disabled","disabled");
    });
}

function swapImg(img,IO){
    img.src = swapImg.getImgSrc(img.src,IO);
}
swapImg.getImgSrc = function(src,IO){
    var pinfo = $php.pathinfo(src);
    var dir = pinfo['dirname'] + '/';
    var file = pinfo['filename'];
    var ext = '.' + pinfo['extension'];
    var baseFile = $php.substr(file, 0, file.length - 1);
    
    if(IO == "I"){
        baseFile += 'B';
    }else{
        baseFile += 'A';
    }
    
    return dir + baseFile + ext;
}

function scanForExternalLinks(context){
    if(!!window.open){
        var useContext = context || $cRoot;
        $('a.external[ClickBound!="bound"]',useContext).attr("ClickBound","bound")
        .click(function(event){
            event.preventDefault();
            window.open(this.href, "_blank");
        })
        .hover(function(){
            scanForExternalLinks.IMG.stop(true,true);
            scanForExternalLinks.IMG.fadeIn(500);
        },
        function(){
            scanForExternalLinks.IMG.stop(true,true);
            scanForExternalLinks.IMG.fadeOut(500);
        })
        .mousemove(function(e){
            scanForExternalLinks.IMG.css({
                'left':e.pageX - 15,
                'top':e.pageY - 15
            });
        });   
    }
}
function scanForTopLinks(context){
    if (!!window.scroll){
        var useContext = context || $cRoot;
        $('a[href="#top"]',useContext).removeAttr('href').click(function(event){
            event.preventDefault();
            window.scrollTop();
        })
    }
}
function scanForRollOvers(context){
    var useContext = context || $cRoot;
    var Imgs = new Array();
    
    $("img.rollover[rollBound!=\"bound\"]",useContext).attr("rollBound","bound").hover(function(){
        swapImg(this,"I");
    },function(){
        swapImg(this,"O");
    }).each(
        function(index,element){
            //Now we preload the rollover image for them
            Imgs[Imgs.length] = swapImg.getImgSrc(element.src,'I');
        }
        );
    preLoadImages(Imgs);
}

////See filemtime.min.js/////
function array_filter(arr,func){var retObj={},k;for(k in arr){if(func(arr[k])){retObj[k]=arr[k];}}
return retObj;}
function date(format,timestamp){var that=this,jsdate,f,formatChr=/\\?([a-z])/gi,formatChrCb,_pad=function(n,c){if((n=n+'').length<c){return new Array((++c)-n.length).join('0')+n;}
return n;},txt_words=["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur","January","February","March","April","May","June","July","August","September","October","November","December"];formatChrCb=function(t,s){return f[t]?f[t]():s;};f={d:function(){return _pad(f.j(),2);},D:function(){return f.l().slice(0,3);},j:function(){return jsdate.getDate();},l:function(){return txt_words[f.w()]+'day';},N:function(){return f.w()||7;},S:function(){var j=f.j();return j>4&&j<21?'th':{1:'st',2:'nd',3:'rd'}[j%10]||'th';},w:function(){return jsdate.getDay();},z:function(){var a=new Date(f.Y(),f.n()-1,f.j()),b=new Date(f.Y(),0,1);return Math.round((a-b)/864e5)+1;},W:function(){var a=new Date(f.Y(),f.n()-1,f.j()-f.N()+3),b=new Date(a.getFullYear(),0,4);return _pad(1+Math.round((a-b)/864e5/7),2);},F:function(){return txt_words[6+f.n()];},m:function(){return _pad(f.n(),2);},M:function(){return f.F().slice(0,3);},n:function(){return jsdate.getMonth()+1;},t:function(){return(new Date(f.Y(),f.n(),0)).getDate();},L:function(){return new Date(f.Y(),1,29).getMonth()===1|0;},o:function(){var n=f.n(),W=f.W(),Y=f.Y();return Y+(n===12&&W<9?-1:n===1&&W>9);},Y:function(){return jsdate.getFullYear();},y:function(){return(f.Y()+"").slice(-2);},a:function(){return jsdate.getHours()>11?"pm":"am";},A:function(){return f.a().toUpperCase();},B:function(){var H=jsdate.getUTCHours()*36e2,i=jsdate.getUTCMinutes()*60,s=jsdate.getUTCSeconds();return _pad(Math.floor((H+i+s+36e2)/86.4)%1e3,3);},g:function(){return f.G()%12||12;},G:function(){return jsdate.getHours();},h:function(){return _pad(f.g(),2);},H:function(){return _pad(f.G(),2);},i:function(){return _pad(jsdate.getMinutes(),2);},s:function(){return _pad(jsdate.getSeconds(),2);},u:function(){return _pad(jsdate.getMilliseconds()*1000,6);},e:function(){throw'Not supported (see source code of date() for timezone on how to add support)';},I:function(){var a=new Date(f.Y(),0),c=Date.UTC(f.Y(),0),b=new Date(f.Y(),6),d=Date.UTC(f.Y(),6);return 0+((a-c)!==(b-d));},O:function(){var tzo=jsdate.getTimezoneOffset(),a=Math.abs(tzo);return(tzo>0?"-":"+")+_pad(Math.floor(a/60)*100+a%60,4);},P:function(){var O=f.O();return(O.substr(0,3)+":"+O.substr(3,2));},T:function(){return'UTC';},Z:function(){return-jsdate.getTimezoneOffset()*60;},c:function(){return'Y-m-d\\Th:i:sP'.replace(formatChr,formatChrCb);},r:function(){return'D, d M Y H:i:s O'.replace(formatChr,formatChrCb);},U:function(){return jsdate.getTime()/1000|0;}};this.date=function(format,timestamp){that=this;jsdate=((typeof timestamp==='undefined')?new Date():(timestamp instanceof Date)?new Date(timestamp):new Date(timestamp*1000));return format.replace(formatChr,formatChrCb);};return this.date(format,timestamp);}
function filemtime(file){var headers={};headers=this.get_headers(file,1);return(headers&&headers['Last-Modified']&&Date.parse(headers['Last-Modified'])/1000)||false;}
function get_headers(url,format){var req=this.window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(!req){throw new Error('XMLHttpRequest not supported');}
var tmp,headers,pair,i,j=0;req.open('HEAD',url,false);req.send(null);if(req.readyState<3){return false;}
tmp=req.getAllResponseHeaders();tmp=tmp.split('\n');tmp=this.array_filter(tmp,function(value){return value.substring(1)!=='';});headers=format?{}:[];for(i in tmp){if(format){pair=tmp[i].split(':');headers[pair.splice(0,1)]=pair.join(':').substring(1);}else{headers[j++]=tmp[i];}}
return headers;}
////////////////////////////

$(function(){
    preLoadImages_urls[preLoadImages_urls.length] = "assets/images/externalLink.png"
    preLoadImages(preLoadImages_urls);
    
    var rootCon = $('div#rootContainer');
    var extImg = $($.IMG({
        'class':'extLink',
        'src':'assets/images/externalLink.png',
        'alt':''
    }));
    
    rootCon.append(extImg);
        
    scanForExternalLinks.IMG = extImg; 
    
    scanForRollOvers(rootCon);
    scanForExternalLinks(rootCon);
    scanForTopLinks(rootCon);
    
    $cRoot = $('div#content',rootCon);
    
    setTimeout(function(){
        var url = location.href || document.URL;
        url = url.split('?');
        url = url[0];
        console.log(url);
        //$("p#modDatePara").show();
        //$("p#modDatePara","span#modDate").html(date("Y-m-d",filemtime(url)));
        $("span#modDate").html(date("Y-m-d",filemtime("assets/getDate.php?file="+url)));
    },500)
});
