function quantum(){

    this.stopEvent = function(e) {
        if (!e) e = window.event;
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }

    this.delete_element = function(el, class_name){
        var panic = 0;
        var container = el.parentNode;
        if(!el)return;
        while(true){
            if(hasClass(container, class_name)){
                var parent = container.parentNode;
                parent.removeChild(container);
                break;
            }
            container = container.parentNode;
            panic++;
            if(panic > 20){
                alert("Possible infinite recursion!");
                return;
            }
        }
    }

    this.move_element = function(ddiv, direction){

        var parent = ddiv.parentNode;
        direction = direction.toLowerCase();

        if (direction == "up")
        {
            var PrevNode = jQuery(parent).prev();
            var PrevNodeTagName = PrevNode[0].tagName.toLowerCase();
            if (PrevNodeTagName == "div")
                jQuery(parent).insertBefore(jQuery(parent).prev());
        }
        else
        {
            var NextNode = jQuery(parent).next();
            var NextNodeTagName = NextNode[0].tagName.toLowerCase();
            if (NextNodeTagName == "div")
                jQuery(parent).insertAfter(jQuery(parent).next());
        }
    }

    this.qLightBox = function(){
        var lb_images = this.qGetLightboxImages();
        for(var x=0; x < lb_images.length; x++){
            var lb = lb_images[x];
            var tq = this;
            this.qAddEventListener(lb, "click",
                function(e){
                    var i = e.target;
                    var nd = document.createElement("div");
                    nd.className = "qLightBox";
                    var cb = document.createElement("div");
                    cb.className = "qLightBoxClose";

                    nd.appendChild(cb);
                    var ndi = document.createElement("img");
                    ndi.src = i.src;
                    nd.appendChild(ndi);
                    var db = tq.qGetBody();
                    db.appendChild(nd);
                    tq.qAddEventListener(cb, "click", function(e){
                       db.removeChild(nd);
                    });
                    tq.qCenterElement(nd);
                }
            );
        }
    };

    this.qGetLightboxImages = function(){
        var qli = this.qGetElementsByTagName("img");
        var em_len = qli.length;
        var images = new Array();
        for(var x=0; x < em_len; x++){
            if(qli[x].className == "qLightBoxImage")images[images.length] = qli[x];
        }
        return images;
    };

    this.qGetElementsByTagName = function(tag, root){
          var els = null;
          tag = tag || '*';
          root = root || document;
          if (typeof(root.getElementsByTagName) != "undefined"){
            els = root.getElementsByTagName(tag);
          }

          if(!els){
              alert("Please Update your browser to at least IE 6 or equivalent. (TagName)");
              return new Array();
          }

          return els;
    };

    this.qGetElementsByClassName = function(classname, root){

          var els = this.qGetElementsByTagName("*",root);
          var c_els = Array();
          for(var x=0; x < els.length; x++){
              //alert(els[x].className);
              //if(els[x].className == classname)c_els[c_els.length] = els[x];
              if(hasClass(els[x], classname))c_els[c_els.length] = els[x];
          }

          return c_els;

          var els = null;
          classname = classname || '*';
          root = root || document;
          if (typeof(root.getElementsByClassName) != "undefined"){
            els = root.getElementsByClassName(classname);
          }

          if(!els){
              alert("Please Update your browser to at least IE 6 or equivalent. (ClassName)");
              return new Array();
          }

          return els;
    };

    this.addOnLoad = function(f){
        if(typeof(f) == "function"){
            this.qAddEventListener(window, "load",f);
        }else alert(f + " is not a function!");
    }

    this.html_entities = function(s){
        //something for Mike to do when he's bored :)
    }

    this.qAddEventListener = function(doc_part, event_type, f){
          if(!(doc_part=this.qGetElement(doc_part))){
              alert("Can't find " + doc_part + " to attach event listener " + f + " to");
              return;
          }
          event_type = event_type.toLowerCase();
          if(doc_part.addEventListener)doc_part.addEventListener(event_type,f, false);
            else if(doc_part.attachEvent)doc_part.attachEvent('on'+event_type,f);
                else alert("Unsupported browser event model");
    }

    this.cancelEvent = function(e){
        e.cancelBubble = true;
        if(e.stopPropagation)e.stopPropagation();
        if(e.preventDefault)e.preventDefault();
    }

    this.qGetElement = function(ele){
        if(typeof(ele)=="string"){
            if(document.getElementById)ele=document.getElementById(ele);
                else if(document.all) ele=document.all[ele];
                    else ele=null;
        }
    return ele;
    }

    this.qCenterElement = function(ele){
        var ww = 0;
        var wh = 0;
        var ew = 0;
        var sx = 0;
        var sy = 0;

        if(window.innerWidth)ww = window.innerWidth;
            else ww = document.clientWidth;

        if(window.innerHeight)wh = window.innerHeight;
            else wh = document.clientHeight;

        if(typeof(window.pageYOffset) == "number"){
            sx = window.pageXOffset;
            sy = window.pageYOffset;
        }else if(typeof(document.body.scrollLeft) == "number"){
            sx = document.body.scrollLeft;
            sy = document.body.scrollTop;
        }
        ele.style.top = sy + "px";
        var dv = document.defaultView;
        var s = dv.getComputedStyle(ele,'');
        ew = s.getPropertyValue("width");
        ew = parseInt(ew);
        var l = (ww-ew)/2;
        ele.style.left = (l + sx) + "px";
    }

    this.test = function(){
        alert("here");
    }

    this.qGetBody = function(){
        return this.qGetElementsByTagName("body")[0];
    }

    this.qGetComputedStyle = function(el, p, i){
      if(!(el=this.qGetElement(el))) return null;
      var s, v = 'undefined', dv = document.defaultView;
      if(dv && dv.getComputedStyle){
        s = dv.getComputedStyle(el,'');
        if (s) v = s.getPropertyValue(p);
      }
      else if(e.currentStyle) {
        v = e.currentStyle[this.qPropCamel(p)];
      }
      else return null;
      return i ? (parseInt(v) || 0) : v;
    }

    this.qPropCamel= function(str){
        var cs = str.split('-');
        var s = str[0];
        for (var i=1; i<cs.length; i++) {
            var c = cs[i].charAt(0);
            s += cs[i].replace(c, c.toUpperCase());
        }
        return s;
    }

    this.qDef = function(){
        for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
        return true;
    }

    this.qPageX = function (ele){
        var x = 0;
        ele = this.qGetElement(ele);
        while (ele) {
        if (this.qDef(ele.offsetLeft)) x += ele.offsetLeft;
            ele = this.qDef(ele.offsetParent) ? ele.offsetParent : null;
        }
        return x;
    }

    this.left = function(el){
        var px = 0;
        if(!(el=this.qGetElement(el)))return 0;
        if(el.style){
            px = parseInt(el.style.left);
            if(isNaN(px)){
                //alert("Non Number");
                px = this.qGetComputedStyle(el,'left',1);
            }
            if(isNaN(px))px=0;
        }
        else if(el.style && el.style.pixelLeft) {
            px=el.style.pixelLeft;
        }else {
            alert("Incompatible browser.");
            return 0;
        }
        //alert(px);
        return px;
    }

    this.top = function(el){
        var px = 0;
        if(!(el=this.qGetElement(el)))return 0;
        if(el.style){
            px = parseInt(el.style.top);
            if(isNaN(px)){
                //alert("Non Number");
                px = this.qGetComputedStyle(el,'top',1);
            }
            if(isNaN(px))px=0;
        }
        else if(el.style && el.style.pixelTop) {
            px=el.style.pixelTop;
        }else {
            alert("Incompatible browser.");
            return 0;
        }
        //alert(px);
        return px;
    }

    this.qEvent = function (ev){
        var e = ev || window.event;
        if (!e) return;

        var qe = new Object();
        qe.type = e.type;
        qe.target = e.target || e.srcElement;
        qe.relatedTarget = e.relatedTarget;
        qe.event = e;
        return qe;
    }


    this.delete_table_row = function(el, class_name1, class_name2){
        var tb = el;
        var tr = null;
        while(true){
            tb = tb.parentNode;
            if(tb.nodeName.toLowerCase() == "tr")tr = tb;
            if(tb.nodeName.toLowerCase() == "table")break;
            if(!tb){
                alert("No table node found. Check page for valid html");
                break;
            }
        }

        var rows = tb.rows;
        for(var x=0; x < rows.length; x++){
            if(rows[x] == tr){
                tb.deleteRow(x);
                break;
            }
        }

        if(class_name1){
            if(!class_name2)class_name2 = class_name1;
            var toggle = true;
            for(var x=1; x < rows.length; x++){
                if(toggle)rows[x].className = class_name1;
                    else rows[x].className = class_name2;
                toggle = !toggle;
            }
        }
    }

    this.synchronous_ajax = function(url, query){
        var aj = false;
        if(!query)query = "";
        if (window.XMLHttpRequest) {
            aj = new XMLHttpRequest();
        } else {
            aj = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (aj){
            aj.open("POST", url, false);
            aj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            aj.send(query);
            return aj.responseText;
        } else {
            return false;
        }
    }

    this.ajax = function(url, callbackFunction, sync){

      var aj=this;
      this.updating = false;
      this.call_back = callbackFunction || function () { };
      this.abort = function()
      {
        if (aj.updating)
        {
          aj.updating=false;
          aj.xhtpr.abort();
          aj.xhtpr=null;
        }
      }
      this.update = function(passData,postMethod)
      {
        if(!passData)passData = "";
        if (aj.updating) {return false;}
        aj.xhtpr = null;
        if (window.XMLHttpRequest)
        {
          aj.xhtpr=new XMLHttpRequest();
        }
        else
        {
          aj.xhtpr=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (aj.xhtpr==null)
        {
          return false;
        }
        else
        {
          aj.xhtpr.onreadystatechange = function()
          {
            if (aj.xhtpr.readyState==4)
            {
              aj.updating=false;
              aj.call_back(aj.xhtpr.responseText,aj.xhtpr.status,aj.xhtpr.responseXML);
              aj.xhtpr=null;
            }
          }
          aj.updating = new Date();
          if (!postMethod || postMethod == "post")
          {
            var uri=urlCall+'?'+aj.updating.getTime();
            aj.xhtpr.open("POST", uri, true);
            aj.xhtpr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            aj.xhtpr.setRequestHeader("Content-Length", passData.length);
            aj.xhtpr.send(passData);
          }
          else
          {
            var uri=urlCall+'?'+passData+'&timestamp='+(aj.updating.getTime());
            aj.xhtpr.open("GET", uri, true);
            aj.xhtpr.send(null);
          }
          return true;
        }
      }
      var urlCall = url;
    }

    this.move_div = function(obj, direction, nesting, container_class){
        var m_div = obj;
        if(!container_class){
            for(var x=0; x < nesting; x++){
                m_div = m_div.parentNode;
            }
            var p_div = m_div.parentNode;
        }else {
            var panic = 0;
            var container = obj.parentNode;
            if(!container)return;
            while(true){
                if(hasClass(container, container_class)){
                    var p_div = container;
                    break;
                }
                m_div = container;
                container = container.parentNode;
                panic++;
                if(panic > 20){
                    alert("Possible infinite recursion!");
                    return;
                }
            }
        }

        var children = p_div.childNodes;
        var em_len = children.length;

        for(var x=0; x < em_len; x++){//remove empty / invalid elements otherwise ordering below will fail.. - can't find any reason in doc source that would cause this, but it happens all the same..
            if(!children[x].innerHTML){
                p_div.removeChild(children[x]);
                x = 0;
                em_len = children.length;
                continue;
            }
        }

        for(var x=0; x < em_len; x++){
            if(children[x] == m_div){
                if(direction == "down"){
                    if(x >= (em_len))return;//already at bottom
                    p_div.insertBefore(m_div,children[x+2]);
                    return;
                }else if(direction == "up"){
                    if(x <= 0){
                        //alert("At Top");
                        return;//already at top
                    }
                    p_div.insertBefore(m_div, children[x-1]);
                    return;
                }
            }//else alert("Children X: " + children[x] + children[x].innerHTML);
        }
    }

    this.add_table_row = function(el, cells){
        var parent = el;
        if(parent.tagName != "TABLE" && el.tagName != "TABLE"){
            while(true){
                parent = parent.parentNode;
                //alert("Parent = " + parent + " & tag_name = " + parent.tagName);
                if(!parent)return;
                if(parent.tagName == "TABLE")break;
            }
        }

        el = parent;
        var new_row = el.insertRow(el.rows.length);
        var cell_count = cells.length;
        for(var x=0; x < cell_count; x++){
            var nc = new_row.insertCell(x);
            nc.innerHTML = cells[x];
        }
    }

    this.move_table_row = function(ddiv, direction, class1, class2, hasHeading){
        var parent = ddiv;
        var move_row = null;
        var new_row = null;
        var new_index = 0;

        direction = direction.toLowerCase();

        while(true){
            parent = parent.parentNode;
            //alert("Parent = " + parent + " & tag_name = " + parent.tagName);
            if(!parent)return;
            if(parent.tagName == "TABLE")break;
            if(parent.tagName == "TR")move_row = parent;
        }

        var item_table = parent;
        var rows = item_table.rows;
        var max = rows.length-1;
        var index = move_row.rowIndex;

        var cells = rows[index].cells;
        var c_len = cells.length;

        var cell_defs = new Array();

        for(var x=0; x < c_len; x++){
            var cell_def = new Object();
            cell_def.html = cells[x].innerHTML;
            cell_def.colspan = cells[x].colSpan;
            cell_def.text_align = getStyle(cells[x], "text-align");
            cell_defs[x] = cell_def;
        }

        if(direction == "down"){
            if(index >= max)return -1;
            item_table.deleteRow(index);
            new_row = item_table.insertRow(index+1);//why is it two not one??? weird
            new_index = index+1;
        }else {
            if(index <= 1 && hasHeading)return;
            if(index <= 0)return -1;
            item_table.deleteRow(index);
            new_row = item_table.insertRow(index-1);//more weirdness, looks like we are inserting a row ontop of the existing one, but we are not.
            new_index = index-1;
            }

        for(var x=0; x < c_len; x++){
            var new_cell = new_row.insertCell(x);
            new_cell.innerHTML = cell_defs[x].html
            //new_cell.width = cells[x].width + "px";
            var colspan = cell_defs[x].colspan;
            if(!colspan)colspan = 1;
            //w_set_attribute(new_cell, "colspan", colspan);
            new_cell.colSpan = "" + colspan;
            //new_cell.colSpan = "2";
            var counter = 0;
            new_cell.style.textAlign = cell_defs[x].text_align;
            /*for(var ss in cells[x].getComputedStyle()) {
                var cs = getStyle(cells[x], ss);
                //alert(cs);
                //counter++;
                //if(counter > 2)break;
                new_cell.style[cs] = ss;
            }*/
           // new_cell.style = cells[x].style;
        }
        this.redo_toggle(item_table, class1, class2);
        return new_index;
    }

    this.redo_toggle = function(table_ob, class1, class2){
        var rows = table_ob.rows;
        var len = rows.length;

        if(!class1)class1 = "qAdminToggle1";
        if(!class2)class2 = "qAdminToggle2";

        var toggle = true;

        for(var x=0; x < len; x++){
            toggle = !toggle;
            var cls = "";
            if(toggle)cls = class1;
                else cls = class2;
            rows[x].className = cls;
        }
    }

    this.send_move_request = function(id, new_index, url){
        var aj = new this.ajax(url);
        aj.call_back = function(response_text){
            if(response_text == "OK"){
                //all ok
                //alert(response_text);
            }
            else {
                alert("Error: " + response_text);
            }
    }
    var query = "id=" + id + "&new_index=" + new_index + "&ajax=true";
    //alert(url + "?" + query);
    aj.update(query);
    }

    this.build_post_data = function(form_name, enc_type){
        var form_ref = null;
        if(!enc_type)enc_type = "url";
        if(typeof(form_name) == "object")form_ref = form_name;
            else form_ref = document.forms[form_name];
        var els = form_ref.elements;

        var em_len = els.length;

        var aj_query = "";

        for(var x=0; x < em_len; x++){
            var new_val = "";
            var new_name = "";
            var el = els[x];
            switch(el.type){
                case "select":
                    new_val = el.options[el.selectedIndex];
                    new_name = el.name;
                    break;

                case "checkbox":
                case "radio":
                    if(el.checked){
                        new_name = el.name;
                        new_val = el.value;
                    }
                    break;

                default:
                    new_name = el.name;
                    new_val = el.value;
            }
            if(!new_name.length)continue;//el was an unchecked tick box or radio button
            //alert("query part = " + aj_query);
            if(!enc_type)enc_type = "url";
            if(enc_type == "url"){
                if(aj_query.length > 0)aj_query += "&";
                aj_query += escape(new_name) + "=" + escape(new_val);
            }else if(enc_type == "json"){//yuk
                if(aj_query.length > 0)aj_query += ",";
                aj_query += new_name + ": " + new_val;
            }
        }
        if(enc_type == "url")aj_query += "&is_ajax=true";
            else aj_query = "{" + aj_query + aj_query + ", is_ajax:true}";
        //alert("query string = " + aj_query);
        return aj_query;
    }

    this.aj_dropdown = function(fo, src, aj_script, ddcallback, selcallback){
        this.fo = fo;
        //this.src = src;
        this.to = null;
        this.ddcallback = ddcallback;
        this.selcallback = selcallback;

        var qq = this;

        var cb = fo;
        var ajd = null;
        while(true){
            cb = cb.parentNode;
            if(!cb)break;
            if(cb.className == "QSearch QBox"){
                ajd = qq.qGetElementsByClassName("aj_drop_div", cb);
                if(!ajd.length){
                    alert("AJ Div not found");
                    return;
                }else ajd = ajd[0];
            }
        }

        qq.qAddEventListener(fo, "keyup", function(e){qq.highlight_row(e);});
        qq.qAddEventListener(fo, "blur", function(e){qq.hide_sel(e);});

        if(!aj_script)aj_script = "/include/ajax/smart_search.php";
            else aj_script = aj_script;

        this.highlight_row = function(e){
            var sd = ajd;
            if(e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 13){//keydown
                var els = qq.qGetElementsByTagName("div", sd);
                var em_len = els.length;
                var got_sel = -1;
                for(var x=0; x < em_len; x++){
                    var el = els[x];
                    if(el.selected_el){
                        //alert("got sel");
                        if(e.keyCode == 40)got_sel = x+1;
                            else if(e.keyCode == 38)got_sel = x-1;
                                else if(e.keyCode == 13){
                                    qq.cancelEvent(e);
                                    this.fo.value = el.innerHTML.replace(/<\/?[^>]+(>|$)/g, "");
                                    this.fo.form.submit();
                                    //alert("??");
                                }
                        el.className = "aj_dropdiv_element";
                        el.selected_el = false;
                    }
                }
                if(got_sel == -1){
                    if(els[0]){
                        els[0].selected_el = true;
                        els[0].className = "aj_dropdiv_element_selected";
                    }
                    }
                    else if(got_sel < em_len){
                        els[got_sel].className = "aj_dropdiv_element_selected";
                        els[got_sel].selected_el = true;
                    }
            }
        }

        this.run_search = function(){
            var ddcallback = this.ddcallback;
            var show_sel = this.show_sel;
            //var fo = this.fo;
            //var t = this;

            var aj = new qq.ajax(aj_script, function(data){
                //alert("Data = " + data);
                if(ddcallback)ddcallback(data);
                qq.show_sel(fo, data);
            });

            var query = "src=" + escape(src) + "&str=" + escape(fo.value);
            //alert(query);
            aj.update(query);
        }

        this.update = function(e){
            if(e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 13){
                //alert("??k");
                if(e.target == fo && e.keyCode == 13){
                    var sd = ajd;
                    var els = qq.qGetElementsByTagName("div", sd);
                    var em_len = els.length;
                    var got_sel = -1;
                    for(var x=0; x < em_len; x++){
                        var el = els[x];
                        if(el.selected_el){
                            qq.cancelEvent(e);
                            return;
                        }
                    }
                    this.fo.form.submit();
                    return;
                }
                qq.cancelEvent(e);
                return;
            }
            if(this.to)clearTimeout(this.to);
            this.to = setTimeout(this.run_search, 100);
        }

        this.show_sel = function(fo, data){
            var pd = fo.parentNode;
            //alert(data);
            //this should all be automatically created / hidden etc but no time today :(
            var sd = ajd;
            sd.style.width = xWidth(fo) + "px";
            sd.innerHTML = "";//dirty dirty...
            data = data.split("#ROW#");
            var em_len = data.length;
            var got_result = false;
            for(var x=0; x < em_len; x++){
                if(!data[x].length)continue;
                var nd = document.createElement("div");
                nd.className = "aj_dropdiv_element";
                var r_id = null;
                var cols = data[x].split("#COL#");
                var txt = "";
                for(var c=0; c < cols.length; c++){
                    if(c == 0){
                        r_id = cols[c];
                        continue;
                    }
                    if(!cols[c].length)continue;
                    if(txt.length)txt += " ";
                    txt += cols[c];
                }
                if(!txt.length)txt = "&nbsp;";
                nd.innerHTML = txt;
                sd.appendChild(nd);
                nd.id = "seldiv_" + r_id;
                var t = this;
                xAddEventListener(nd, "click", function(e){t.select_row(e);});
                got_result = true;
            }
            if(got_result){
                //alert("b");
                sd.style.display = "block";
            }
            else {
                //alert("dn");
                sd.style.display = "none";
            }
        }

        this.select_row = function(e){
            //alert(e.target + " id = " + xv.target.id);
            //alert(e.target);
            var tg = e.target;
            if(!tg.id)tg = tg.parentNode;
            var tid = tg.id.split("_")[1];
            if(this.selcallback)this.selcallback(tid);
            var ti = tg.innerHTML.toLowerCase();
            if(ti == "&nbsp;")this.fo.value = "";
                else if(src == "U"){
                    var parts = ti.split(" ");
                    var dstr = "";
                    var em_len = parts.length;
                    for(var x=0; x < 2; x++){
                        if(x > 0)dstr += " ";
                        dstr += parts[x];
                    }
                fo.value = dstr;
                }else fo.value = tg.innerHTML.replace(/<\/?[^>]+(>|$)/g, "");
                //alert(fo.value);
                //alert(tg.id);
            ajd.innerHTML = "";
            ajd.style.display = "none";
            this.hide_sel(e);
        }

        this.hide_sel = function(e){
            //alert(e.target);
            //for(a in e)console.log(a + e.a);
            setTimeout(function(){ajd.style.display = 'none';}, 100);
            //var sd = ajd;
            //sd.innerHTML = "";
            //sd.style.display = "none";
        }
    return this;
    }

}

//dirty hack to keep old fader code working until we can improve it

function hasClass(ele,cls) {
    if(!ele)return false;
    if(!ele.className)return false;
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
    if(!ele)return false;
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
    ele.className.replace(/ +/g,' ');
}

function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,'');
    }
}

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}


//Additions to JS May2011
function confirmationDelete()
    {var answer = confirm("Are you sure you want to Delete this item?");//alert(answer);
         if (answer){return true;}else{return false;}
    }

function w_get_attribute(el, attr_name){
    var wt_len = el.attributes.length;
    for(var wt=0; wt < wt_len; wt++){
        //if(!el.attributes[wt])continue;
        //alert("attr node name = " + el.attributes[wt].nodeName);
        //alert("attr node value = " + el.attributes[x].nodeValue);
        if(el.attributes[wt].nodeName == attr_name)return el.attributes[wt].nodeValue;
        }
    return 0;
    }

function w_set_attribute(el, attr_name, new_value){
    var em_len = el.attributes.length;
        var existing = false;
    for(var at=0; at < em_len; at++){
        //alert("attr node name = " + el.attributes[x].nodeName);
        //alert("attr node value = " + el.attributes[x].nodeValue);
        if(el.attributes[at].nodeName == attr_name){
                    el.attributes[at].nodeValue = new_value;
                    existing = true;
                }
        }
        if(!existing){
            if(typeof(el.createAttribute)!= "undefined")el.createAttribute(attr_name, new_value);
            el.setAttribute(attr_name, new_value);
        }
    return 0;
    }

var q = new quantum();//get the 'q' object ready in case of need
var qlib = new quantum();//I fear something in jquery below is taking over the q variable, so create qlib as well

// MR

$(document).ready(function() {
    // Alt attribute = default value
    $('.input_hint').each(function() {
        if($(this).val() == '') {
            $(this).val($(this).attr('alt'));
        }
    });
    $('.input_hint').live('focus', function() {
        if($(this).val() == $(this).attr('alt')) {
            $(this).val('');
        }
    }).live('blur', function() {
        if($(this).val() == '') {
            $(this).val($(this).attr('alt'));
        }
    });

    // Alt attribute = default value on focus
    $('.input_hint_reverse').each(function() {
        $(this).focus(function() {
            if($(this).val() == '') {
                $(this).val($(this).attr('alt'));
            }
        }).blur(function() {
            if($(this).val() == $(this).attr('alt')) {
                $(this).val('');
            }
        });
    });

    // Set height of all children to be height of the tallest child
    $('.inline_child_heights').each(function() {
        var newHeight = 0;
        $(this).children().each(function() {
            var thisHeight = $(this).height();
            if(thisHeight > newHeight) {
                newHeight = thisHeight;
            }
        });
        $(this).children.each(function() {
            $(this).css('height', newHeight);
        });
    });

    // Slide up / down on click
        $('div.data_set_head').each(function() {
            if(!$(this).hasClass('box_open')) {
                $(this).siblings('div.data_set_cont').hide();
                $(this).addClass('box_close');
            }
        });
        $('div.data_set_head:not(:animated)').click(function() {
            //$('div.data_set_cont:visible').slideUp(500);
            var sib_sel = $(this).siblings('div.data_set_cont:first');
            if(sib_sel.not(':animated')) {
                if(sib_sel.is(':hidden')) {
                    sib_sel.slideDown(500);
                } else {
                    sib_sel.slideUp(500);
                }
                if($(this).hasClass('box_open')) {
                    $(this).removeClass('box_open').addClass('box_close');
                } else {
                    $(this).assClass('box_open').removeClass('box_close');
                }
            }
        });
    // End slide up / down on click
    // Slide up / down on click Ver 2 (next class in list shown/hidden)
        $('.slide_v_head').click(function() {
            var nextClass = false;
            var class_list = $(this)[0].className.split(/\s+/);
            if(class_list.length > 1) {
                for(i = 0; i < class_list.length; i++) {
                    if(class_list[i] == "slide_v_head") {
                        nextClass = i + 1;
                        if(!class_list[nextClass]) {
                            nextClass = false;
                            break;
                        }
                        nextClass = class_list[nextClass];
                        break;
                    }
                }
                if(nextClass) {
                    $('.slide_v_cont.auto_close').each(function() {
                        if($(this).not(':hidden') && !$(this).hasClass(nextClass)) {
                            $(thi).removeClass('box_open').addClass('box_close');
                            $(this).stop(true, true).slideUp(500);
                        }
                    });
                    var thi = $(this);
                    $('.' + nextClass).each(function() {
                        if($(this).hasClass('slide_v_cont')) {
                            if($(this).is(':hidden')) {
                                $(thi).addClass('box_open').removeClass('box_close');
                                $(this).stop(true, true).slideDown(500);
                            } else {
                                $(thi).removeClass('box_open').addClass('box_close');
                                $(this).stop(true, true).slideUp(500);
                            }
                        }
                    });
                }
            }
            return false;
        });
        $('.slide_v_head').each(function() {
            if($(this).hasClass('box_open')) {
                return true;
            }
            var nextClass = false;
            var class_list = $(this)[0].className.split(/\s+/);
            if(class_list.length > 1) {
                for(i = 0; i < class_list.length; i++) {
                    if(class_list[i] == "slide_v_head") {
                        nextClass = i + 1;
                        if(!class_list[nextClass]) {
                            nextClass = false;
                            break;
                        }
                        nextClass = class_list[nextClass];
                        break;
                    }
                }
            }
            if(nextClass) {
                var thi = $(this);
                $('.' + nextClass).each(function() {
                    if($(this).hasClass('slide_v_cont')) {
                        $(this).hide();
                        thi.addClass('box_close');
                    }
                });
            }
        });
    // End slide up / down on click Ver 2 (next class in list shown/hidden)
    // Click = bring up tiny MCE editor
        $('.edit_expand').live('click', function() {
            var hInput = $(this).find('input[type=hidden]').first();
            $.fancybox({
                'type': 'iframe',
                'href': '/admin/mce.php?input=' + encodeURI('input[name=\''+ hInput.attr('name') + '\']') + '&data=' + encodeURI(hInput.val()),
                'showCloseButton': false,
                'hideOnOverlayClick': false,
                'enableEscapeButton': false,
                'autoDimensions': false,
                'width': 780,
                'height': 700,
                'onCleanup': function() {
                    hInput.val($('#fancybox-frame').contents().find('textarea').val());
                }
            });
        });
    // End Click = bring up tiny MCE editor
});

// Set height of elements in a class to be the same
// Usage: $('#parent_id').mSetHeight('linked_class_name');
(function($) {$.fn.mSetHeights = function(className) {var argLen = arguments.length;if(argLen < 1) {alert('mSetHeights expects a minimum of 1 parameter. ' + argLen + ' given.');return false;}return this.each(function() {var elems = $(this).find('.' + className);var maxHeight = 0;elems.each(function() {var thisHeight = $(this).height();if(thisHeight > maxHeight) {maxHeight = thisHeight;}});elems.each(function() {$(this).css('height', maxHeight);});});}})(jQuery);

var scrollTop = 0;
function get_scrollTop() {
    scrollTop = $(window).scrollTop();
    return scrollTop;
}
function set_scrollTop() {
    $(window).scrollTop(scrollTop);
}

// Menu click to show subs
    $(document).ready(function() {
        $('.menubar_click').each(function() {
            $(this).addClass('nohover');
            $(this).find('a').click(function(e) {
                var sibUl = $(this).siblings('ul.menubar:first');
                if(sibUl.length > 0) {
                    if(sibUl.not('.inanimation')) {
                        sibUl.addClass('inanimation');
                        if(sibUl.is(':hidden')) {
                            $(this).parents('.menubar_click').find('.menubar:visible').each(function() {
                                if($(this).find(sibUl).length == 0) {
                                    $(this).addClass('inanimation').slideUp(500, function() {
                                        $(this).removeClass('inanimation');
                                    });
                                }
                            });
                            $(this).parent().addClass('active');
                            sibUl.slideDown(500, function() {
                                $(this).removeClass('inanimation');
                            });
                        } else {
                            $(this).parent().removeClass('active');
                            sibUl.slideUp(500, function() {
                                $(this).removeClass('inanimation');
                            });
                        }
                    }
                    e.preventDefault();
                    return false;
                }
            });
        });
    });
// END menu click to show subs

// Clock
    $(document).ready(function() {
        $('#clock').each(function() {
            var hourC = $(this).find('.hours:first');
            var minC = $(this).find('.minutes:first');
            var secC = $(this).find('.seconds:first');

            var hours = parseInt(hourC.html());
            var mins = parseInt(minC.html());
            var secs = parseInt(secC.html());

            clock_ticker($(this), hours, mins, secs);
        });
    });

    function clock_ticker(thi, hoursI, minsI, secsI) {
        var th = thi;
        var hours = parseInt(hoursI);
        var mins = parseInt(minsI);
        var secs = parseInt(secsI);

        var hourC = th.find('.hours:first');
        var minC = th.find('.minutes:first');
        var secC = th.find('.seconds:first');

        if(secs < 59) {
            secs += 1;
        } else {
            if(mins < 59) {
                secs = 0;
                mins += 1;
            } else {
                secs = 0;
                mins = 0;
                if(hours < 23) {
                    hours += 1
                } else {
                    hours = 0;
                    window.location.reload();
                }
            }
        }

        hourC.html(pad_num(hours, 2));
        minC.html(pad_num(mins, 2));
        secC.html(pad_num(secs, 2));

        setTimeout(function() {
            clock_ticker(th, hours, mins, secs);
        }, 1000);
    }
// END clock

// Pad number to a certain length
function pad_num(num, len) {
    num = num + '';
    while(num.length < len) {
        num = '0' + num;
    }
    return num;
}

// Adds class to THIS object and removes it from elsewhere.
//<a onclick=”class_toggle(this, ‘some_class_name);”>
function class_toggle(e, className) {
    $('.' + className).each(function() {
        $(this).removeClass(className);
    });
    $(e).addClass(className);
}

$(document).ready(function() {
    $('.m_image_upload').find('label').live('click', function() {
        var thi = $(this).parents('.m_image_upload:first');
        var extraUrl = '';
        if(thi.find('span.settings').length > 0) {
            extraUrl = thi.find('span.settings:first').html();
        }
        $.fancybox({
            'type': 'iframe',
            'href': '/admin/image_management/m_image_uploader.php' + extraUrl,
            'autoDimensions': false,
            'width': 1000,
            'height': 700,
            'onCleanup': function() {
                thi.find('input[type=hidden]').val($('#fancybox-frame').contents().find('input#return_image').val());
            }
        });
    });
    $('.gallery_popup').each(function() {
        var thi = $(this);
        thi.click(function(e) {
            $.fancybox({
                          'type' : 'iframe',
                          'href' : thi.attr('href'),
                'autoDimensions' : false,
                         'width' : 1000,
                        'height' : 700
            });
            e.preventDefault();
            return false;
        });
    });
    $('a.fancybox_gallery').attr('rel', 'gallery').fancybox({
        'cyclic': true
    });
});

// END MR

// toggle an object on the screen. usage as follows
//onclick="$('.thingImChanging').mClassToggle('active');"
//onclick="$('.wrapper').find('.childclass').mClassToggle('active');"

(function($) {
    $.fn.mClassToggle = function(classToToggle) {
        this.each(function() {
            if($(this).hasClass(classToToggle)) {
                $(this).removeClass(classToToggle);
            } else {
                $(this).addClass(classToToggle);
            }
        });
    }
})(jQuery);




// PW //
function hideClass(hideClass){
    $('.' + hideClass).each(function(index) {
        $(this).hide();
    });
    $('.control' + hideClass).html('<span class="controlShow" onclick="showClass(\'' + hideClass + '\');">&nbsp;</span>');
}

function showClass(hideClass){
    $('.' + hideClass).each(function(index) {
        $(this).show();
    });
    $('.control' + hideClass).html('<span class="controlHide" onclick="hideClass(\'' + hideClass + '\');">&nbsp;</span>');
}

function hideFrontEndClass(hideClass){
    $('.' + hideClass).each(function(index) {
        $(this).hide();
    });
    $('.control' + hideClass).html('<span class="button controlShow" onclick="showFrontEndClass(\'' + hideClass + '\');">View</span>');
}

function showFrontEndClass(hideClass){
    $('.' + hideClass).each(function(index) {
        $(this).show();
    });
    $('.control' + hideClass).html('<span class="button controlHide" onclick="hideFrontEndClass(\'' + hideClass + '\');">Hide</span>');
}
// END PW
//news / category / product results per page code

function set_rpp(ro){
    var uri = new String(document.location);
    var gp = uri.split("?");
    var ex_args = "";
    if(gp.length > 1)ex_args = gp[1];
    var base_loc = gp[0];
    var args = ex_args.split("&");
    var news_args = "";
    var em_len = args.length;
    for(var x=0; x < em_len; x++){
        var arg = args[x].split("=");
        if(arg[0] == "rpp")continue;
        if(news_args.length)news_args += "&";
        news_args += args[x];
    }
    if(news_args.length)news_args += "&";
    news_args += "rpp=" + ro.value;
    document.location = base_loc + "?" + news_args;
}


function print_content(element_id) {
    var content = $('#'+element_id).html();
    var pwin    = window.open('', 'print_content', 'width=100,height=100');

    pwin.document.open();
    pwin.document.write('<html><head></head><body id="print_content" onload="window.print()">' + content + '</body></html>');
    pwin.document.close();

    setTimeout(function() { pwin.close(); }, 1000);
}

/**  HTML ELEMENT FUNCTIONS  **/
/*****************************************************************************/

    function textarea_character_limit(textarea, limit) {

        var text = $(textarea).val();
        var textlength = text.length;
        if(textlength > limit) {
            $(textarea).val(text.substr(0, limit));
            $(textarea).siblings('.character-limit').find('input').val(0);
            return false;
        } else {
            $(textarea).siblings('.character-limit').find('input').val(limit - textlength);
            return true;
        }
    }

/*****************************************************************************/
