﻿var  fontSizeChanger= {
    sizeUnit:       "px",
    defaultSize:    11,
    maxSize:        15,
    minSize:        11,
        queryName:      "dw_fsz",   // name to check query string for when passing size in URL
    queryNum:       true,       // check query string for number only (eg. index.html?18 )
    izmeruSaraksts:     [],         // set method populates

     setParams: function(unitType, default_Size, minimalSize, maximalSize, sels) { //setParams
        this.sizeUnit = unitType;       
        this.defaultSize = default_Size;
        this.maxSize = maximalSize;          
        this.minSize = minimalSize;
        if (sels) this.set(default_Size, minimalSize, maximalSize, sels);
    },

    set: function (default_Size, minimalSize, maximalSize, sels) { 
        var ln = this.izmeruSaraksts.length;        
        for (var i=0; sels[i]; i++) {
            this.izmeruSaraksts[ln+i] = [];
            this.izmeruSaraksts[ln+i]["sel"]  = sels[i];
            this.izmeruSaraksts[ln+i]["default_Size"] = default_Size;
            this.izmeruSaraksts[ln+i]["min"]   = minimalSize || this.minSize;
            this.izmeruSaraksts[ln+i]["max"]   = maximalSize || this.maxSize;
            // hold ratio of this selector's default size to this.defaultSize for calcs in adjust fn 
            this.izmeruSaraksts[ln+i]["ratio"] = this.izmeruSaraksts[ln+i]["default_Size"] / this.defaultSize;
        }
    },

    // fontu izmera mainitaja konstruktors
    load: function() {
        if ( !document.getElementById || !document.getElementsByTagName ) return;
        var size, sizerEl, i;
        // check query string and cookie for fontSize
        // check size (in case default unitType changed or size passed in url out of range)
        size = getValueFromQueryString( this.queryName, this.queryNum );
        if ( isNaN( parseFloat(size) ) || size > this.maxSize || size < this.minSize ) {
            size = getCookie("fontSize");
            if ( isNaN( parseFloat(size) ) || size > this.maxSize || size < this.minSize ) {
                size = this.defaultSize;
            }
        } 
        this.curSize = this.defaultSize;  // create curSize property to use in calculations 
        sizerEl = document.getElementById('sizer');
        if (sizerEl) sizerEl.style.display = "block";
        // if neither set nor  setParams populates izmeruSaraksts, apply sizes to body and td's
        if (this.izmeruSaraksts.length == 0) {
            this. setParams( this.sizeUnit, this.defaultSize, this.minSize, this.maxSize, [] );
        }
        if ( size != this.defaultSize ) this.adjust( size - this.defaultSize );
    }
    ,

    // pielago izmerus ar soli
    adjust: function(n) {
        if ( !this.curSize ) return; 
        var alist, size, list, i, j;
        // check against max/minSize
        if ( n > 0 ) {
            if ( this.curSize + n > this.maxSize ) n = this.maxSize - this.curSize;
        } else if ( n < 0 ) {
            if ( this.curSize + n < this.minSize ) n = this.minSize - this.curSize;
        }
        if ( n == 0 ) return;
        this.curSize += n;
        // loop through izmeruSaraksts, calculating size, checking max/min
        alist = this.izmeruSaraksts;
        for (i=0; alist[i]; i++) {
            size = this.curSize * alist[i]['ratio']; // maintain proportion 
            size = Math.max(alist[i]['min'], size); size = Math.min(alist[i]['max'], size);
            list = getElementsBySelector( alist[i]['sel'] );						
            for (j=0; list[j]; j++) {list[j].style.fontSize = size + this.sizeUnit; }
        }
        setCookie( "fontSize", this.curSize, 180, "/" );
    },

    // Atrgiez sakotnejos iestadijumus
    reset: function() {
        if ( !this.curSize ) return; 
        var alist = this.izmeruSaraksts, list, i, j;
        for (i=0; alist[i]; i++) {
            //panem elementus
            list = getElementsBySelector( alist[i]['sel'] );
            for (j=0; list[j]; j++) { 
                // Reset izmeruSaraksts elements to their default sizes
                //list[j].style.fontSize = alist[i]['default_Size'] + this.sizeUnit;
                list[j].style.fontSize = '';  // restores original font size
            } 
        }
        this.curSize = this.defaultSize;
        // dzees kuukas
        deleteCookie("fontSize", "/");
    }
};

// panem elementu no sarasta ar tagiem
function getElementsBySelector(selector) {
    if (!document.getElementsByTagName) return [];
    var nodeList = [document], tokens, bits, list, col, els, i, j, k;
    selector = selector.normalize();
    tokens = selector.split(' ');
    for (i=0; tokens[i]; i++) {
        if ( tokens[i].indexOf('#') != -1 ) {  // id
            bits = tokens[i].split('#'); 
            var el = document.getElementById( bits[1] );
            if (!el) return []; 
            if ( bits[0] ) {  // check tag
                if ( el.tagName.toLowerCase() != bits[0].toLowerCase() ) return [];
            }
            for (j=0; nodeList[j]; j++) {  // check containment
                if ( nodeList[j] == document || dw_contained(el, nodeList[j]) ) 
                    nodeList = [el];
                else return [];
            }
        } else if ( tokens[i].indexOf('.') != -1 ) {  // class
            bits = tokens[i].split('.'); col = [];
            for (j=0; nodeList[j]; j++) {
                els = getElementsByClass( bits[1], bits[0], nodeList[j] );
                for (k=0; els[k]; k++) { col[col.length] = els[k]; }
            }
            nodeList = [];
            for (j=0; col[j]; j++) { nodeList.push(col[j]); }
        } else {  // element 
            els = []; 
            for (j = 0; nodeList[j]; j++) {
                list = nodeList[j].getElementsByTagName(tokens[i]);
                for (k = 0; list[k]; k++) { els.push(list[k]); }
            }
            nodeList = els;
        }
    }
    return nodeList;
};

// panem elementus pec klases
function getElementsByClass(sClass, sTag, oCont) {
    var result = [], list, i;
    var re = new RegExp("\\b" + sClass + "\\b", "i");
    oCont = oCont? oCont: document;
    if ( document.getElementsByTagName ) {
        if ( !sTag || sTag == "*" ) {
            list = oCont.all? oCont.all: oCont.getElementsByTagName("*");
        } else {
            list = oCont.getElementsByTagName(sTag);
        }
        for (i=0; list[i]; i++) 
            if ( re.test( list[i].className ) ) result.push( list[i] );
    }
    return result;
};

// 2nd arg: return whole query string if varName not found?
// (compatible with previous version, which just checked for number after ?)
function getValueFromQueryString(varName, bReturn) {
    var val = "";
    if (window.location.search) {
        var qStr = window.location.search.slice(1);
        var ar = qStr.split("&");
        var get = [], ar2;
        // portion before = becomes index (like $_GET)
        for (var i=0; ar[i]; i++) {
            if ( ar[i].indexOf("=") != -1 ) {
                ar2 = ar[i].split("=");
                get[ ar2[0] ] = ar2[1];
            }
        }
        val = get[varName];
        // if varName is not passed to this function or not found, return entire query string ?      
        if ( !val && bReturn ) {
            val = qStr;
        }
    }
    return val;
};

// returns true of oNode is contained by oCont (container)
function dw_contained(oNode, oCont) {
    if (!oNode) return; // in case alt-tab away while hovering (prevent error)
    while ( oNode = oNode.parentNode ) if ( oNode == oCont ) return true;
    return false;
};

if (!Array.prototype.push) {  // ie5.0
	Array.prototype.push =  function() {
		for (var i=0; arguments[i]; i++) this[this.length] = arguments[i];
		return this[this.length-1]; // return last value appended
	}
};

String.prototype.normalize = function() {
	var re = /\s\s+/g;
	return this.trim().replace(re, " ");
};

String.prototype.trim = function() {
	var re = /^\s+|\s+$/g;
	return this.replace(re, "");
};


/*********************************************************************************
  Cepumi
**********************************************************************************/
function setCookie(name,value,days,path,domain,secure) {
  var expires, date;
  if (typeof days == "number") {
    date = new Date();
    date.setTime( date.getTime() + (days*24*60*60*1000) );
		expires = date.toGMTString();
  }
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie(name) {
  var nameq = name + "=";
  var c_ar = document.cookie.split(';');
  for (var i=0; i<c_ar.length; i++) {
    var c = c_ar[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameq) == 0) return unescape( c.substring(nameq.length, c.length) );
  }
  return null;
}
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}
