/*#############################################################
Name: Niceforms
Version: 1.0
Author: Lucian Slatineanu
URL: http://www.badboy.ro/

Feel free to use and modify but please provide credits.

Modified By Terry
URL: http://www.1dress.cn/terry/article.asp?id=4
Fix select bugs.

Modified by Biro Creative
URL: birocreative.com
Works for <select> tags only
#############################################################*/
//Global Variables
var niceforms = document.getElementsByTagName('form');
var selects = new Array();
var selectText = "Please select";
var agt = navigator.userAgent.toLowerCase();
this.ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
//var hovers = new Array();
//var buttons = new Array();
var isMac = new RegExp('(^|)'+'Apple'+'(|$)');

//Theme Variables - edit these to match your theme
var selectRightSideWidth = 13;
var selectLeftSideWidth = 0;
//var selectAreaHeight = 32;
var selectAreaOptionsOverlap = 2;
var imagesPath = "niceforms/";

//Initialization function - if you have any other 'onload' functions, add them here
function init() {
    //don't use niceforms for IE6 or IE7
    if(!document.getElementById || navigator.appVersion.indexOf('MSIE 6.0') != -1
        || navigator.appVersion.indexOf('MSIE 7.0') != -1) {return false;}
    
    getElements();
    replaceSelects();
}

//getting all the required elements
function getElements() {
    var re = new RegExp('(^| )'+'niceform'+'( |$)');
    for (var nf = 0; nf < document.getElementsByTagName('form').length; nf++)
    {
        if (re.test(niceforms[nf].className))
        {
            for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName('select').length; nfs++) {
                selects.push(document.forms[nf].getElementsByTagName('select')[nfs]);
            }
        }
    }
}

function replaceSelects() {
    for(var q = 0; q < selects.length; q++) {
        //create and build div structure
        var selectArea = document.createElement('div');
        var left = document.createElement('div');
        var right = document.createElement('div');
        var center = document.createElement('div');
        var button = document.createElement('a');
        var text = document.createTextNode(selectText);
        center.id = "mySelectText"+q;
        //get width and height
        var vParameter = selects[q].className.split("_");
        var selectWidth = parseInt(vParameter[1]);
        var selectHeight = parseInt(vParameter[3]);
        var styleheight = selects[q].offsetHeight-2;
        
        if (navigator.appName == 'Microsoft Internet Explorer') {
            center.style.marginTop = -styleheight - 4 + 'px';
            center.style.marginLeft = '12px';
        }
        else if (navigator.userAgent.indexOf('Firefox/3') != -1) {
            center.style.marginTop = -(styleheight - 21)/2 + 'px';
            center.style.marginLeft = '12px';
        }
        center.style.width = selectWidth + 'px';
        selectArea.style.width = selectWidth + selectRightSideWidth + selectLeftSideWidth + 'px';
        button.style.width = selectWidth + selectRightSideWidth + selectLeftSideWidth + 'px';
        button.style.marginLeft = - selectWidth - selectLeftSideWidth +30 + 'px';
        button.href = "javascript:showOptions("+q+")";
        button.onkeydown = selectEvent;
        button.className = "selectButton"; //class used to check for mouseover
        selectArea.className = "selectArea";
        selectArea.id = "sarea"+q;
        left.className = "left";
        right.className = "right";
        center.className = "center";
        right.appendChild(button);
        center.appendChild(text);
        selectArea.appendChild(left);
        selectArea.appendChild(right);
        selectArea.appendChild(center);
        //hide the select field
        selects[q].style.display='none'; 
        //insert select div
        selects[q].parentNode.insertBefore(selectArea, selects[q]);
        //build & place options div
        var optionsDiv = document.createElement('div');
        optionsDiv.style.width = selectWidth + 7 + 'px';
        //set height
        var totalHeight = selects[q].options.length*18;
        if(selectHeight<totalHeight) {
            optionsDiv.style.height = selectHeight+'px';
        }
        optionsDiv.style.overflow = 'auto';
        optionsDiv.className = "optionsDivInvisible" + ' ' + selects[q].id;
        optionsDiv.id = "optionsDiv"+q;
        optionsDiv.style.left = (findPosX(selectArea) -1) + 'px';
        //optionsDiv.style.top = findPosY(selectArea) + selectAreaHeight - selectAreaOptionsOverlap + 'px';
        if (navigator.appVersion.indexOf('Safari') != -1) {
            optionsDiv.style.top = findPosY(selectArea) + styleheight + 10 + 'px';
        }
        else {
            optionsDiv.style.top = findPosY(selectArea) + styleheight + 'px';
        }
        
        //get select's options and add to options div
        for(var w = 0; w < selects[q].options.length; w++) {
            var optionHolder = document.createElement('p');
            var optionLink = document.createElement('a');
            var optionTxt = document.createTextNode(selects[q].options[w].text);
            optionLink.href = "javascript:showOptions("+q+"); selectMe('"+selects[q].id+"',"+w+","+q+");";
            optionLink.appendChild(optionTxt);
            optionHolder.appendChild(optionLink);
            optionsDiv.appendChild(optionHolder);
            //check for pre-selected items
            if(selects[q].options[w].selected) {selectMe(selects[q].id,w,q);}
        }
        //insert options div
        document.getElementsByTagName("body")[0].appendChild(optionsDiv);
    }
}
function showOptions(g) {
        elem = document.getElementById("optionsDiv"+g);
        
        // names[0] = optionsDivInvisible | optionsDivVisible
        // names[1] = classname to identify type of select field
        var names = elem.className.split(" ");
        
        if (names[0]=="optionsDivInvisible") {
            elem.className = "optionsDivVisible" + ' ' + names[1];
        }
        else if (names[0]=="optionsDivVisible") {
            elem.className = "optionsDivInvisible" + ' ' + names[1];
        }
        
        // reset z-index of all selects
        for(var i=0;i<selects.length;i++)
        {
        	var tempelem = document.getElementById('optionsDiv'+i);
        	if(tempelem!=null)
        	{
        		tempelem.style.zIndex = 20;
        	}
        }
        
        elem.style.zIndex = 21;
        
        elem.onmouseout = hideOptions;
}
//Any good solution ?
function hideOptions(e) { //hiding the options on mouseout
//  if (!e) var e = window.event;
//  var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
//  if(((reltg.nodeName != 'A') && (reltg.nodeName != 'DIV')) || ((reltg.nodeName == 'A') && (reltg.className=="selectButton") && (reltg.nodeName != 'DIV'))) {this.className = "optionsDivInvisible";};
//  e.cancelBubble = true;
//  if (e.stopPropagation) e.stopPropagation();
}
function selectMe(selectFieldId,linkNo,selectNo) {
    //feed selected option to the actual select field
    var originalSelectionIndex = -1;
    var newSelectionIndex = originalSelectionIndex;
    selectField = document.getElementById(selectFieldId);
    for(var k = 0; k < selectField.options.length; k++) {
    		if(selectField.options[k].selected) { 
    			originalSelectionIndex = k;
    		}
        if(k==linkNo) {
        	selectField.options[k].selected = "selected";
        	newSelectionIndex = k;
        }
        else {selectField.options[k].selected = "";}
    }
    
    // if defined & appropriate, fire onChange event
    if((typeof(selectField.onchange)=='function') && (originalSelectionIndex!=newSelectionIndex))
    {
    	selectField.onchange();
    }
    
    //show selected option
    textVar = document.getElementById("mySelectText"+selectNo);
    var newText = document.createTextNode(selectField.options[linkNo].text);
    textVar.replaceChild(newText, textVar.childNodes[0]);
}
function selectEvent(e) {
    if (!e) var e = window.event;
    var thecode = e.keyCode;
    switch(thecode){
        case 40: //down
            var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
            var linkNo = 0;
            for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
            ++linkNo;
            if(linkNo >= selects[fieldId].options.length) {linkNo = 0;}
            selectMe(selects[fieldId].id, linkNo, fieldId);
            break;
        case 38: //up
            var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
            var linkNo = 0;
            for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
            --linkNo;
            if(linkNo < 0) {linkNo = selects[fieldId].options.length - 1;}
            selectMe(selects[fieldId].id, linkNo, fieldId);
            break;
        default:
            break;
    }
}

//Useful functions
function findPosY(obj) {
    var posTop = 0;
    while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
    if(this.ie) posTop += document.body.offsetTop; //added
    return posTop;
}
function findPosX(obj) {
    var posLeft = 0;
    while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
    if(this.ie) posLeft += document.body.offsetLeft; //added
    return posLeft;
}

window.onload = init;
