var g_largeDialogWrapMarginTopBottom = 20;
var g_largeDialogWidthwrap = 920;
var g_colorsInited = false;

function zoom(zoomPath) {
    var dirtyMagicNumber = 54;
    var height = viewportGetHeight() - dirtyMagicNumber;
    var html = '<div class="zoomImage" id="zoomImage" style="height: ' + height + 'px;">' +
            '<img src="' + zoomPath + '" alt="" id="zoomImageImg" /></div>';
    showLargeDialog(html);
    return false;
}

function viewportGetHeight() {
    var retval = 0;
    if (window.innerHeight)
        retval = window.innerHeight - 18;
    else if (document.documentElement && document.documentElement.clientHeight) 
        retval = document.documentElement.clientHeight;
    else if (document.body && document.body.clientHeight) 
        retval = document.body.clientHeight;
    return retval;    
}

function showLargeDialog(html) {
    closeLargeDialog();
    var height = viewportGetHeight() - g_largeDialogWrapMarginTopBottom;

    var closeButton = '<a href="javascript:closeLargeDialog()" class="largeDialogCancelButton">' +
            '<img src="/image-site/close.png" alt="[Close]" /></a>';

    var bodyElm = document.body;

    var wrapShade = document.createElement('div');
    bodyElm.appendChild(wrapShade);
    wrapShade.id = 'largeDialogWrapperShade';
    wrapShade.style.top = getLargeDialogTop(g_largeDialogWrapMarginTopBottom) + 'px';
    wrapShade.style.height = ( viewportGetHeight() - g_largeDialogWrapMarginTopBottom ) + 'px';
    wrapShade.style.left = ( viewportGetWidth() / 2 - g_largeDialogWidthwrap / 2) + 'px';
    wrapShade.innerHTML = '&nbsp;';

    var wrap = document.createElement('div');
    bodyElm.appendChild(wrap);
    wrap.id = 'largeDialogWrapper';
    wrap.style.top = getLargeDialogTop(g_largeDialogWrapMarginTopBottom) + 'px';
    wrap.style.height = ( viewportGetHeight() - g_largeDialogWrapMarginTopBottom ) + 'px';
    wrap.style.left = ( viewportGetWidth() / 2 - g_largeDialogWidthwrap / 2) + 'px';

    wrap.setAttribute( 'onclick', 'closeLargeDialog()' );
    wrap.onclick = function() { closeLargeDialog(); };

    wrap.innerHTML = closeButton + html;
}

function closeLargeDialog() {
    var elm = document.getElementById('largeDialogWrapper');
    if (elm) {
        document.body.removeChild(elm);
        document.body.removeChild( document.getElementById('largeDialogWrapperShade') );
    }
}

function getLargeDialogTop(wrapperMarginTopBottom) {
    return Math.round( viewportGetScrollY() + wrapperMarginTopBottom );
}

function viewportGetScrollY() {
    var retval = 0;
    if (typeof window.pageYOffset == "number")
        retval = window.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
        retval = document.documentElement.scrollTop;
    else if (document.body && document.body.scrollTop) 
        retval = document.body.scrollTop; 
    else if (window.scrollY)
        retval = window.scrollY;
    return retval;
}

function viewportGetWidth() {
    var retval = 0;
    if (window.innerWidth)
        retval = window.innerWidth - 18;
    else if (document.documentElement && document.documentElement.clientWidth) 
        retval = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth) 
        retval = document.body.clientWidth;
    return retval;    
}

function toggleColorBox() {
    if (!g_colorsInited) { initColors(); }
    Misc.toggleElm('colorBox');
}

function initColors() {
    var colors = ['0,0,0','0,0,60','0,0,120','0,0,180','0,0,255','0,60,0','0,60,60','0,60,120','0,60,180','0,60,255','0,120,0','0,120,60','0,120,120','0,120,180','0,120,255','0,180,0','0,180,60','0,180,120','0,180,180','0,180,255','0,255,0','0,255,60','0,255,120','0,255,180','0,255,255','60,0,0','60,0,60','60,0,120','60,0,180','60,0,255','60,60,0','60,60,60','60,60,120','60,60,180','60,60,255','60,120,0','60,120,60','60,120,120','60,120,180','60,120,255','60,180,0','60,180,60','60,180,120','60,180,180','60,180,255','60,255,0','60,255,60','60,255,120','60,255,180','60,255,255','120,0,0','120,0,60','120,0,120','120,0,180','120,0,255','120,60,0','120,60,60','120,60,120','120,60,180','120,60,255','120,120,0','120,120,60','120,120,120','120,120,180','120,120,255','120,180,0','120,180,60','120,180,120','120,180,180','120,180,255','120,255,0','120,255,60','120,255,120','120,255,180','120,255,255','180,0,0','180,0,60','180,0,120','180,0,180','180,0,255','180,60,0','180,60,60','180,60,120','180,60,180','180,60,255','180,120,0','180,120,60','180,120,120','180,120,180','180,120,255','180,180,0','180,180,60','180,180,120','180,180,180','180,180,255','180,255,0','180,255,60','180,255,120','180,255,180','180,255,255','255,0,0','255,0,60','255,0,120','255,0,180','255,0,255','255,60,0','255,60,60','255,60,120','255,60,180','255,60,255','255,120,0','255,120,60','255,120,120','255,120,180','255,120,255','255,180,0','255,180,60','255,180,120','255,180,180','255,180,255','255,255,0','255,255,60','255,255,120','255,255,180','255,255,255'];

    var boxes = [];
    var rgb = [Misc.getGetParam('r'), Misc.getGetParam('g'), Misc.getGetParam('b')];
    var rgb2 = [Misc.getGetParam('r2'), Misc.getGetParam('g2'), Misc.getGetParam('b2')];
    for (var i = 0, max = colors.length; i < max; i++) {
        var thisRgb = colors[i].split(',');
        var isTargetColor = rgb[0] == thisRgb[0] && rgb[1] == thisRgb[1] && rgb[2] == thisRgb[2];
        var isTargetColor2 = rgb2[0] == thisRgb[0] && rgb2[1] == thisRgb[1] && rgb2[2] == thisRgb[2];

        var style = 'background-color: rgb(' + colors[i] + ');';
        if (isTargetColor) {
            style += 'background-image: url(/image-site/colorsearch-rectangle.png)';
        }
        else if (isTargetColor2) {
            style += 'background-image: url(/image-site/colorsearch-cross.png)';
        }

        boxes[i] = '<div style="' + style + '" ' +
                'onclick="colClick(this)" oncontextmenu="colRClick(this)"></div>';
    }
    var html = boxes.join('');
    Misc.setHtml('colorBox', html);
}

function colClick(elm) {
    var rgb = getColorsFromStyle(elm.style.backgroundColor);
    elm.style.backgroundImage = 'url(/image-site/colorsearch-rectangle.png)';
    loadPage('/search?r=' + rgb[0] + '&g=' + rgb[1] + '&b=' + rgb[2]);
}

function colRClick(elm) {
    var rgb = [Misc.getGetParam('r'), Misc.getGetParam('g'), Misc.getGetParam('b')];
    var rgb2 = getColorsFromStyle( elm.style.backgroundColor );
    if (rgb[0] == null) {
        alert("Right-clicking defines a secondary color, but you haven't defined a primary color with left-click yet.");
    }
    else if (rgb[0] == rgb2[0] && rgb[1] == rgb2[1] && rgb[2] == rgb2[2]) {
        alert("Right-clicking defines a secondary color, which needs to be different from this primary color.");
    }
    else {
        elm.style.backgroundImage = 'url(/image-site/colorsearch-cross.png)';
        var url = '/search?' +
                'r=' + rgb[0] + '&g=' + rgb[1] + '&b=' + rgb[2] + '&' +
                'r2=' + rgb2[0] + '&g2=' + rgb2[1] + '&b2=' + rgb2[2];
        loadPage(url);
    }
    return false;
}

function loadPage(url) {
    document.location.href = url;
}

function getColorsFromStyle(sStyle) {
    var rgb = sStyle;
    rgb = Misc.doReplace(rgb, 'rgb(', '');
    rgb = Misc.doReplace(rgb, ')', '');
    rgb = Misc.doReplace(rgb, ', ', ',');
    return rgb.split(',');
}

/*** Array object ***/

Array.prototype.toUnique = function() {
    var r = new Array();
    o:for (var i = 0, n = this.length; i < n; i++) {
        for (var x = 0, y = r.length; x < y; x++) {
            if (r[x] == this[i] || r[x] + ' ' == this[i] + ' ') {
                continue o;
            }
        }
        r[r.length] = this[i];
    }
    return r;
}

Array.prototype.inArray = function(v) {
    var isIt = false;
    for (var i = 0; i < this.length; i++) {
        if (this[i] == v) {
            isIt = true;
            break;
        }
    }
    return isIt;
}

Array.prototype.removeItem = function(toRemove) {
    // or use splice... http://codepunk.hardwar.org.uk/ajs44.htm
    var r = new Array();
    var max = this.length;
    for (var i = 0; i < max; i++) {
        if (this[i] != toRemove) {
            r[r.length] = this[i];
        }
    }
    return r;
}

/*** String object ***/

String.prototype.ucFirst = function() {
    var f = this.charAt(0).toUpperCase();
    return f + this.substr(1, this.length - 1);
}

String.prototype.toXml = function() {
    return Misc.toXml(this);
}

String.prototype.toName = function(allowUpperCase) {
    return Misc.toName(this, allowUpperCase);
}

String.prototype.toAttribute = function() {
    return Misc.toAttribute(this);
}

String.prototype.trim = function() {
    var s = this;
    if (s) {
        s = s.replace(new RegExp("^[ ]+", "g"), "");
        s = s.replace(new RegExp("[ ]+$", "g"), "");
    }
    return s;
}

String.prototype.cutLength = function(maxLength) {
    if (!maxLength) { maxLength = 20; }
    var value = this;
    var ender = '...';
    if (this.length - ender.length > maxLength) {
        value = this.substr(0, maxLength - ender.length) + ender;
    }
    return value;
}

String.prototype.ucWords = function() {
    if (this) {
        var str = this;
        return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
    }
}

String.prototype.getTextBetween = function(sFrom, sTo) {
    var sPart = '';
    var iFrom = this.indexOf(sFrom);
    var iTo = this.indexOf(sTo, iFrom);
    iFrom += sFrom.length;
    if (iTo > iFrom) { sPart = this.substring(iFrom, iTo); }
    return sPart;
}

String.prototype.replaceAll = function(sFind, sReplace) {
    var s = this;
    var sOld = null;
    while (sOld != s) {
        sOld = s;
        s = s.replace(sFind, sReplace);
    }
    return s;
}

/*** Misc object ***/

function Misc() {
}

Misc.getElm = function(id) {
    return document.getElementById(id);
}

Misc.getCreateElement = function(id) {
    var elm = document.getElementById(id);
    if (!elm) {
        elm = document.createElement('div');
        elm.setAttribute('id', id);
        document.body.appendChild(elm);
    }
    return elm;
}

Misc.toggleElm = function(id) {
    var elm = document.getElementById(id);
    if (elm) {
        if (elm.style.display == 'block') {
            elm.style.display = 'none';
        }
        else {
            elm.style.display = 'block';
        }
    }
}

Misc.isShowing = function(id) {
    var isShowing = false;
    var elm = document.getElementById(id);
    if (elm) { isShowing = elm.style.display == 'block'; }
    return isShowing;
}

Misc.showElm = function(id) {
    var elm = document.getElementById(id);
    if (elm) { elm.style.display = 'block'; }
}

Misc.hideElm = function(id) {
    var elm = document.getElementById(id);
    if (elm) { elm.style.display = 'none'; }
}

Misc.getHtml = function(id) {
    var html;
    var elm = document.getElementById(id);
    if (elm) {
        html = elm.innerHTML;
    }
    else {
        // alert('Element ' + id + ' not found.');
    }
    return html;
}

Misc.setHtml = function(id, html) {
    var elm = document.getElementById(id);
    if (elm) {
        if (navigator.appName == 'Microsoft Internet Explorer') {
            innerHtmlWorkaroundForIExplorer8(elm, html);
        }
        else {
            elm.innerHTML = html;
        }
    }
    else {
        // alert('Element ' + id + ' not found.');
    }
}

Misc.getRandomString = function() {
    var chars = '0123456789abcdefghiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var stringLength = 64;
    var randomString = '';
    for (var i=0; i < stringLength; ++i) {
        var rnum = Math.floor( Math.random() * chars.length );
        randomString += chars.substring(rnum, rnum + 1);
    }
    return randomString;
}

Misc.toXml = function(s) {
    if (s || s == 0) {
        s = s.toString();
        s = s.replace(/&/g, '&amp;');
        s = s.replace(/</g, '&lt;');
        s = s.replace(/>/g, '&gt;');
    }
    else {
        s = '';
    }
    return s;
}

Misc.toAttribute = function(s) {
    if (s) {
        s = s.toString();
        s = Misc.toXml(s);
        s = s.replace(/"/g, '&quot;');
        // todo: s = s.replace(/'/g, '&#145;');
    }
    else {
        s = '';
    }
    return s;
}

Misc.toName = function(s, allowUpperCase) {
    var name = '';
    if (!allowUpperCase) { s = s.toLowerCase(); }
    var allowed = [
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
            '0','1','2','3','4','5','6','7','8','9', '_'];
    if (allowUpperCase) {
        var max = allowed.length;
        for (var i = 0; i < max; ++i) {
            var allowedUpper = allowed[i].toUpperCase();
            if (allowedUpper != allowed[i]) {
                allowed[allowed.length] = allowedUpper;
            }
        }
    }
    for (var i = 0; i < s.length; ++i) {
        var letter = s.substring(i, i + 1);
        if ( allowed.inArray(letter) ) { name += letter; }
    }
    return name;
}

Misc.getChars = function(char, numberOfChars) {
    var s = '';
    for (var i = 1; i <= numberOfChars; i++) {
        s += char;
    }
    return s;
}

Misc.forceMinMax = function(v, min, max) {
    if (v < min) {
        v = min;
    }
    else if (v > max) {
        v = max;
    }
    return v;
}

Misc.getRandomInt = function(min, max) {
    return Math.floor( ( (max + 1 - min) * Math.random() ) + min );
}

Misc.getFormValue = function(id) {
    var v = '';
    var elm = document.getElementById(id);
    if (elm) { v = Misc.getElmFormValue(elm); }
    return v;
}

Misc.getElmFormValue = function(elm) {
    var v = '';
    switch (elm.type) {
        case 'checkbox':
            v = elm.checked;
            break;
        default:
            v = elm.value;
    }
    return v;
}

Misc.setFormValue = function(id, v) {
    var elm = document.getElementById(id);
    if (elm) {
        elm.value = v;
    }
}

Misc.preloadImage = function(url) {
    var img =  new Image();
    img.src = url;
}

Misc.pad = function(v) {
    if ( (v+'').length == 1) { v = '0' + v; }
    return v;
}

Misc.focusElm = function(id) {
    var elm = document.getElementById(id);
    if (elm) { elm.focus(); }
}

Misc.setOpacity = function(elm, opacityFloat) {
    elm.style.MozOpacity = opacityFloat;
    elm.style.opacity = opacityFloat;
}

Misc.elmExists = function(id) {
    return !!document.getElementById(id);
}

Misc.escapeRegex = function(s) {
    return s.replace(/([\\\^\$>*+[\]?{}.=!:(|)])/g, '\\$1');
}

Misc.doReplace = function(sAll, sFind, sReplace, caseSensitive) {
    var sFind = Misc.escapeRegex(sFind);
    var regexFind = new RegExp( sFind, (caseSensitive ? 'g' : 'gi') );
    return sAll.replace(regexFind, sReplace);
}

Misc.ucWords = function(s) {
    return (typeof s == 'string') ? s.ucWords() : null;
}

Misc.getParam = function(id) {
    var thisValue = null;
    var hash = parent.location.hash;
    if (hash != '') {
        var params = hash.substring(1);
        if ( params.indexOf('=') >= 0) {
            var nameValues = params.split('&');
            for (var i = 0; i < nameValues.length; ++i) {
                var nameValue = nameValues[i].split('=');
                if (id == nameValue[0]) {
                    thisValue = nameValue[1];
                    break;
                }
            }
        }
    }
    return thisValue;
}

Misc.getGetParam = function(name) {
    // via netlobo.com/url_query_string_javascript.html
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null ) {
        return '';
    }
    else {
        return results[1];
    }
}

function innerHtmlWorkaroundForIExplorer8(el, html) {
    // via Jon Fox
    if (el) {
        var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
        var newEl = document.createElement(oldEl.nodeName);

        newEl.id = oldEl.id;
        newEl.className = oldEl.className;

        newEl.innerHTML = html;
        if(oldEl.parentNode) {
            oldEl.parentNode.replaceChild(newEl, oldEl);
        }
        else {
            oldEl.innerHTML = html;
        }
        return newEl;
    }
}
