// /////////////////////////////////////////////////////////////////////////////////////////////////
// Application:  Website
//        File:  local/CSCC.js
//      Author:  Andrew Deans (deansa@clarkstate.edu)
//     Created:  15 September 2008
//     Updated:  06 October 2009
// Description:  General helper routines used throughout the website.
//   Changelog:  06 October 2009
//                 - Added CSCC.MSIE variable.
//               08 October 2008
//                 - Added function SetFormFieldState.
// /////////////////////////////////////////////////////////////////////////////////////////////////

// If our namespace object does not exist go ahead and create it.
if (!CSCC) var CSCC = new Object();



// replaceAll //////////////////////////////////////////////////////////////////////////////////////
// Replaces all instances of Search in the string with Replace.
// /////////////////////////////////////////////////////////////////////////////////////////////////
String.prototype.replaceAll = function(Search, Replace)
{
    var str = this;
    var index = str.indexOf(Search);
     
    // Keep looping while an instance of the target string
    // still exists in the string.
    while (index != -1)
    {
        // Relace out the current instance.
        str = str.replace(Search, Replace);
         
        // Get the index of any next matching substring.
        index = str.indexOf(Search);
    }
     
    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return str;
}



// AddOption ///////////////////////////////////////////////////////////////////////////////////////
// Adds a shiny new option to the dropdown box with the given id.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.AddOption = function(DropdownId, Value, Text)
{
    var p;
    
    p = document.createElement('option');
    p.value = Value;
    p.text = Text;
    
    document.getElementById(DropdownId).options.add(p);
}



// IsInternetExplorer //////////////////////////////////////////////////////////////////////////////
// Returns true/false to indicate if we are running under IE or not.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.IsMSIE = null;
CSCC.IsInternetExplorer = function()
{
    if (CSCC.IsMSIE === null)
        CSCC.IsMSIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
    //Math.max(navigator.userAgent.toLowerCase().indexOf('msie'), 0);
    
    return CSCC.IsMSIE;
} 



// OffsetTop ///////////////////////////////////////////////////////////////////////////////////////
// Calculates the given element's offset (in pixels) from the top of the page.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.OffsetTop = function(Element)
{
    if (!Element) return 0;
    return Element.offsetParent ? Element.offsetTop + CSCC.OffsetTop(Element.offsetParent) : Element.offsetTop;
}



// OffsetLeft //////////////////////////////////////////////////////////////////////////////////////
// Calculates the given element's offset (in pixels) from the left side of the page.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.OffsetLeft = function(Element)
{
    if (!Element) return 0;
    return Element.offsetParent ? Element.offsetLeft + CSCC.OffsetLeft(Element.offsetParent) : Element.offsetLeft;
}



// AddCssClass /////////////////////////////////////////////////////////////////////////////////////
// Appends the given class to the field's list of classes.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.AddCssClass = function(Field, ClassName)
{
    if (!Field || !ClassName) return;
    
    if (Field.getAttribute('class'))
    {
        if (Field.getAttribute('class').indexOf(ClassName) < 0)
        {
            Field.setAttribute('class', Field.getAttribute('class') + ' ' + ClassName);
        }
    }
    else
    {
        Field.setAttribute('class', ClassName);
    }
    
    if (Field.getAttribute('className'))
    {
        if (Field.getAttribute('className').indexOf(ClassName) < 0)
        {
            Field.setAttribute('className', Field.getAttribute('className') + ' ' + ClassName);
        }
    }
    else
    {
        Field.setAttribute('className', ClassName);
    }
}



// RemoveCssClass //////////////////////////////////////////////////////////////////////////////////
// Removes the given class from the field's list of classes.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.RemoveCssClass = function(Field, ClassName)
{
    if (!Field || !ClassName) return;
    
    if (Field.getAttribute('class') && Field.getAttribute('class').indexOf(ClassName) > -1)
    {
        Field.setAttribute('class', Field.getAttribute('class').replace(ClassName, ''));
    }
    
    if (Field.getAttribute('className') && Field.getAttribute('className').indexOf(ClassName) > -1)
    {
        Field.setAttribute('className', Field.getAttribute('className').replace(ClassName, ''));
    }
}



// AttachStylesheet ////////////////////////////////////////////////////////////////////////////////
// Dynamically adds a stylesheet to the document. The TargetDoc parameter may be used to add the
// stylesheet to another window but defaults to the current one.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.AttachStylesheet = function(StylesheetUrl, Media, TargetDoc)
{
    var css;
    var link;
    
    if (!StylesheetUrl) return;
    if (!Media) Media = "screen";
    if (!TargetDoc) TargetDoc = window.document;
    
    if(TargetDoc.createStyleSheet)
    {
        TargetDoc.createStyleSheet(StylesheetUrl);
    }
    else
    {
        css = "@import url('" + StylesheetUrl + "');";
        link = TargetDoc.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'data:text/css,' + escape(css);
        TargetDoc.getElementsByTagName("head")[0].appendChild(link);
    }
}



// EscapeUrl ///////////////////////////////////////////////////////////////////////////////////////
// Custom escape function. We use this instead of the more usual escape() to ensure the string is
// escaped in the way we want. The escape() function will do stupid things like encode '&' as
// '&amp;', which doesn't play well with our proxy script.
// /////////////////////////////////////////////////////////////////////////////////////////////////
CSCC.EscapeUrl = function(Url)
{
    var chars = [ [ '%', '%25' ],
                  [ ':', '%3A' ],
                  [ '/', '%2F' ],
                  [ '.', '%2E' ],
                  [ '?', '%3F' ],
                  [ '&', '%26' ],
                  [ '=', '%3D' ] ];
    var p;
    
    for (p = 0; p < chars.length; p++)
    {
        Url = Url.replaceAll(chars[p][0], chars[p][1]);
    }
    
    return Url;
}


// Extends the Date object by adding a strftime function.
// http://hacks.bluesmoon.info/strftime/
Date.ext={};Date.ext.util={};Date.ext.util.xPad=function(x,pad,r){if(typeof (r)=="undefined"){r=10}for(;parseInt(x,10)<r&&r>1;r/=10){x=pad.toString()+x}return x.toString()};Date.prototype.locale="en-GB";if(document.getElementsByTagName("html")&&document.getElementsByTagName("html")[0].lang){Date.prototype.locale=document.getElementsByTagName("html")[0].lang}Date.ext.locales={};Date.ext.locales.en={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],x:"%d/%m/%y",X:"%T"};Date.ext.locales["en-US"]=Date.ext.locales.en;Date.ext.locales["en-US"].c="%a %d %b %Y %r %Z";Date.ext.locales["en-US"].x="%D";Date.ext.locales["en-US"].X="%r";Date.ext.locales["en-GB"]=Date.ext.locales.en;Date.ext.locales["en-AU"]=Date.ext.locales["en-GB"];Date.ext.formats={a:function(d){return Date.ext.locales[d.locale].a[d.getDay()]},A:function(d){return Date.ext.locales[d.locale].A[d.getDay()]},b:function(d){return Date.ext.locales[d.locale].b[d.getMonth()]},B:function(d){return Date.ext.locales[d.locale].B[d.getMonth()]},c:"toLocaleString",C:function(d){return Date.ext.util.xPad(parseInt(d.getFullYear()/100,10),0)},d:["getDate","0"],e:["getDate"," "],g:function(d){return Date.ext.util.xPad(parseInt(Date.ext.util.G(d)/100,10),0)},G:function(d){var y=d.getFullYear();var V=parseInt(Date.ext.formats.V(d),10);var W=parseInt(Date.ext.formats.W(d),10);if(W>V){y++}else{if(W===0&&V>=52){y--}}return y},H:["getHours","0"],I:function(d){var I=d.getHours()%12;return Date.ext.util.xPad(I===0?12:I,0)},j:function(d){var ms=d-new Date(""+d.getFullYear()+"/1/1 GMT");ms+=d.getTimezoneOffset()*60000;var doy=parseInt(ms/60000/60/24,10)+1;return Date.ext.util.xPad(doy,0,100)},m:function(d){return Date.ext.util.xPad(d.getMonth()+1,0)},M:["getMinutes","0"],p:function(d){return Date.ext.locales[d.locale].p[d.getHours()>=12?1:0]},P:function(d){return Date.ext.locales[d.locale].P[d.getHours()>=12?1:0]},S:["getSeconds","0"],u:function(d){var dow=d.getDay();return dow===0?7:dow},U:function(d){var doy=parseInt(Date.ext.formats.j(d),10);var rdow=6-d.getDay();var woy=parseInt((doy+rdow)/7,10);return Date.ext.util.xPad(woy,0)},V:function(d){var woy=parseInt(Date.ext.formats.W(d),10);var dow1_1=(new Date(""+d.getFullYear()+"/1/1")).getDay();var idow=woy+(dow1_1>4||dow1_1<=1?0:1);if(idow==53&&(new Date(""+d.getFullYear()+"/12/31")).getDay()<4){idow=1}else{if(idow===0){idow=Date.ext.formats.V(new Date(""+(d.getFullYear()-1)+"/12/31"))}}return Date.ext.util.xPad(idow,0)},w:"getDay",W:function(d){var doy=parseInt(Date.ext.formats.j(d),10);var rdow=7-Date.ext.formats.u(d);var woy=parseInt((doy+rdow)/7,10);return Date.ext.util.xPad(woy,0,10)},y:function(d){return Date.ext.util.xPad(d.getFullYear()%100,0)},Y:"getFullYear",z:function(d){var o=d.getTimezoneOffset();var H=Date.ext.util.xPad(parseInt(Math.abs(o/60),10),0);var M=Date.ext.util.xPad(o%60,0);return(o>0?"-":"+")+H+M},Z:function(d){return d.toString().replace(/^.*\(([^)]+)\)$/,"$1")},"%":function(d){return"%"}};Date.ext.aggregates={c:"locale",D:"%m/%d/%y",h:"%b",n:"\n",r:"%I:%M:%S %p",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"};Date.ext.aggregates.z=Date.ext.formats.z(new Date());Date.ext.aggregates.Z=Date.ext.formats.Z(new Date());Date.ext.unsupported={};Date.prototype.strftime=function(fmt){if(!(this.locale in Date.ext.locales)){if(this.locale.replace(/-[a-zA-Z]+$/,"") in Date.ext.locales){this.locale=this.locale.replace(/-[a-zA-Z]+$/,"")}else{this.locale="en-GB"}}var d=this;while(fmt.match(/%[cDhnrRtTxXzZ]/)){fmt=fmt.replace(/%([cDhnrRtTxXzZ])/g,function(m0,m1){var f=Date.ext.aggregates[m1];return(f=="locale"?Date.ext.locales[d.locale][m1]:f)})}var str=fmt.replace(/%([aAbBCdegGHIjmMpPSuUVwWyY%])/g,function(m0,m1){var f=Date.ext.formats[m1];if(typeof (f)=="string"){return d[f]()}else{if(typeof (f)=="function"){return f.call(d,d)}else{if(typeof (f)=="object"&&typeof (f[0])=="string"){return Date.ext.util.xPad(d[f[0]](),f[1])}else{return m1}}}});d=null;return str};


CSCC.WriteNewsDate = function(Published)
{
    var pub = new Date(Published);
    var now = new Date();
    var style;
    var pubText;
    
    if (pub < now) style = 'date-inactive';
    else           style = '';
    
    pubText = (pub.getMonth() + 1) + '/' + pub.getDate() + '/' + pub.getFullYear();
    
    document.write('<span class="date ' + style + '">Published: ' + pubText + '</span>');
}
