﻿/// <reference path="jquery-1.4.2-vsdoc.js" />
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/* Hint: CR7682 */
function Jump(newurl)
{
    if (newurl == 'skip') return;
    result = newurl.split('|');
    url = result[0];
    target = result[1];
    
    if (target == '_blank') {
        window.open(url, "", "menubar=1,status=1,location=1,toolbar=1,scrollbars=1,resizable=1,width=640,height=480");
    } else {
        window.location.href = url;
    }
}

function go(newurl)
{
    if (newurl == null || newurl == '') return;
    if (newurl == 'skip') return;
    if (newurl.indexOf('|') > 0) {
        Jump(newurl);
    }  else {
        window.location.href = newurl;
    }
}

function openEnlargeImageFromPage(url) {
    var soPageURL;
    soPageURL = new String(window.location.href);
    i1 = soPageURL.indexOf('http://');
    if (i1 >= 0) soPageURL = escape(soPageURL.substring(7, soPageURL.length));

    contactus = window.open(url, "productimage", "width=740,height=600,toolbar=0,titlebar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=1,copyhistory=0,alwaysRaised=1");
    contactus.focus();
}

function openPartnerContactFromPage(url) {
    var soPageURL;
    soPageURL = new String(window.location.href);
    i1 = soPageURL.indexOf('http://');
    if (i1 >= 0) soPageURL = escape(soPageURL.substring(7, soPageURL.length));

    contactus = window.open(url, "partnerContact", "width=538,height=600,toolbar=0,titlebar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=1,copyhistory=0,alwaysRaised=1");
    contactus.focus();
}

function hexEncode(invalue) {
	return "%" + invalue.toString(16);
}

function utfEncode(inputstring) {
	outcode = "";
	for (a=0; a<inputstring.length; a++) {
		c = inputstring.charCodeAt(a);
		// Code characters to UTF-8 and append to outcode
		if (c < 0x80){
			outcode += inputstring.charAt(a); 
		} else if (c < 0x800){
 			outcode += hexEncode((0xC0 | c>>6));
			outcode += hexEncode((0x80 | c & 0x3F));
		} else if (c < 0x10000) {
			outcode += hexEncode((0xE0 | c>>12));
			outcode += hexEncode((0x80 | c>>6 & 0x3F));
			outcode += hexEncode((0x80 | c & 0x3F)); 
		} else if (c < 0x200000) {
			outcode += hexEncode((0xF0 | c>>18));
			outcode += hexEncode((0x80 | c>>12 & 0x3F));
			outcode += hexEncode((0x80 | c>>6 & 0x3F));
			outcode += hexEncode((0x80 | c & 0x3F));
		}
	}
	return outcode;
}

function openSalesContacts(scCategory,scCountry,language)
{
  href = document.URL;
  if (scCategory && scCategory.length > 3 && scCategory!="|Feedback")
  {
    window.open("http://www02.abb.com" + scCategory + "&SCref=" + href + "&SC", "Feedback","width=578,height=600,resizable=yes,toolbar=no,titlebar=yes,status=no,scrollbar=yes,menubar=no,location=no");
  }
}

function onChangeCountryCategory(scCat,cntry)
{
    if (scCat != "" & scCat != "skip" & cntry !="skip")
    {
        href = document.URL;
        var language = "";
        var link = "/global/seitp/seitp179.nsf/frmWebFrameset?ReadForm&SClang=" + language + "&SCcat=" + scCat + "&SCcountry=" + cntry + "&SCref=" + href + "&SC";
        openSalesContacts(link,cntry);
    }
}

function openUrl( urlStr, target )
{
  if( target == '' ){
    this.window.location.href = urlStr;
  }
  else if(parent.frames[target]){
    parent.frames[target].document.location = urlStr;
  }
  else if( parent.parent.frames[target] ){
    parent.parent.frames[target].document.location = urlStr;
  }
  else {
    window.open( urlStr, target );
  } 
}

function replaceUrl( urlStr, target )
{
  re = /viewInside/gi;
  newUrl=urlStr.replace(re, "0");
  re = /\$percent\$/gi;
  pos = newUrl.indexOf( 'javascript' );
  fixedUrl = "";
  if( pos > -1 ) {
     eval( newUrl.replace( re, '%' ) );
  }
  else {
     i1 = newUrl.indexOf('://');
     if (i1 > 0 && (target == '' || target == 'main' || target == 'content' || target == 'left' || target == '_self' )) {
        newUrl = newUrl;
     }
     else {
        newUrl = newUrl.replace( re, '%' );
     }
  openUrl( newUrl, target );
  }
}

function getCookie(name) {
  var cookieString = document.cookie;
  var valueStart = cookieString.indexOf(name);
  if(valueStart == -1) {
    return null;
  }
  valueStart += name.length + 1;
  var valueEnd = cookieString.indexOf(";", valueStart);
  if(valueEnd == -1) {
    valueEnd = cookieString.length;
  }
  var value = cookieString.substring(valueStart, valueEnd);
  return unescape(value);
}

//function: setCookieExp
//scope: local but general
//purpose: stores a cookie
//param: nam - name of the cookie
//param: val - value of the cookie
//param: day - expiration time in days
function setCookieExp(nam,val,day) {
	var exp=new Date();
	exp.setTime(exp.getTime()+day*86400000);
	document.cookie=nam+'='+escape(val)+'; expires='+exp.toGMTString()+';path=/';
}

//function: setCookie
//purpose: setCookieExp with default expiration in 365 days
//see: setCookieExp()
function setCookie(nam,val) {
	setCookieExp(nam,val,365);
}

function openWin( urlStr, name, parameters ){
	newWin = window.open(urlStr, name, parameters);
	newWin.focus();
}

function getSelectedValue(id) {
	var selector = document.getElementById(id);
	return selector.options[selector.options.selectedIndex].value;
}


var progressEnd = 10;
var progressColor = '#D5D9DF'; // set to progress bar color
var progressInterval = 500;	// (milli-seconds)
var progressAt = 0;
var progressTimer;

function progress_clear() {
    for (var i = 1; i <= progressEnd; i++)
	    document.getElementById('progress'+i).style.backgroundColor = 'transparent';
    progressAt = 0;
}

function progress_update() {
    centerProgressBarInFrame();
    progressAt++;
    if (progressAt > progressEnd)
	    progress_clear();
    else
	    document.getElementById('progress'+progressAt).style.backgroundColor = progressColor;
    progressTimer = setTimeout('progress_update()',progressInterval);
}

function progress_stop() {
    clearTimeout(progressTimer);
    progress_clear();
}

function centerProgressBarInFrame() {
    /*
    var frameHeight = parseInt(document.body.clientHeight);
    var scrollPosition = parseInt(document.body.scrollTop);
    document.getElementById('progressBar').style.top = ((frameHeight-100)/2 + scrollPosition) + 'px';
    */
}

function displayProgressBar() {
    centerProgressBarInFrame();
    progress_stop();
    document.getElementById('progressBar').style.visibility = 'visible';
    progress_update();
}

function goToTopOfPage()
{
    try
    {
        document.location.href = "#";
        window.scrollTo(0,0);
    }
    catch (err)
    {
    }
}

function autofitIframe()
{
    if (iframeID)
    {
        $('#' + iframeID).each(function () { 
            var minimumFrameHeight = 400;
            var heightOfFooterAndMargin = $('#footer').height() + 30; // 30 for margin
            var heightOfHeaderAndMargin = $('#headerRegion').height() + 25; // 25 for margin
            var hegihtOfContentHead = 0;
            if ($('#contentHead').is('*'))
            {
                if ($('#contentHead').height() > 0)
                    hegihtOfContentHead = $('#contentHead').height() + 15; // 15 for margin
                else
                    hegihtOfContentHead = 100 + 15; // 15 for margin. 100 as guess of unloaded mast header
            }

            var iFrameHeight = ($(window).height() + $(window).scrollTop()) - (heightOfHeaderAndMargin + heightOfFooterAndMargin + hegihtOfContentHead);

            if (iFrameHeight < minimumFrameHeight)
                iFrameHeight = minimumFrameHeight;

            if ($('#navigationRegion').is('*'))
            {
                var heightOfNavigationRegion = $('#navigationRegion').height();
                if (iFrameHeight < heightOfNavigationRegion)
                    iFrameHeight = heightOfNavigationRegion;
            }
            if ($('#resourceRegion').is('*'))
            {
                var heightOfResourceRegion = $('#resourceRegion').height();
                if (iFrameHeight < heightOfResourceRegion)
                    iFrameHeight = heightOfResourceRegion;
            }
            
            $(this).css('height', iFrameHeight + 'px');
            $(this).parent().css('height', iFrameHeight + 'px');
        })
    }
} 

function hasCookiesEnabled()
{
    setCookie('hasCookie', 'true');
    var cookie = getCookie('hasCookie');
    return (cookie == 'true');
}

function setCookie (name, value, lifespan, access_path) {
    var cookietext = name + "=" + encodeURIComponent(value);
    if (lifespan != null) {
      var today=new Date()
      var expiredate = new Date()
      expiredate.setTime(today.getTime() + 1000*60*60*24*lifespan)
      cookietext += "; expires=" + expiredate.toGMTString()
    }
    if (access_path != null) {
      cookietext += "; PATH="+access_path
    }
    document.cookie = cookietext
    return null
}

function getCookie(Name) {
    var search = Name + "="
    var CookieString = document.cookie
    var result = null
    if (CookieString.length > 0) {
        offset = CookieString.indexOf(search)
        if (offset != -1) {
            offset += search.length
            end = CookieString.indexOf(";", offset)
            if (end == -1) {
               end = CookieString.length }
            result = unescape(CookieString.substring(offset, end))
       }
    }
    return result
}

function openContactusFromPage(contacturl)
{
    var soPageURL;
    var server = '';
    var linkServerIndex = contacturl.indexOf('http://');
    if (linkServerIndex >=0)
    {
        server = ''
    }
    else
    {
        server = 'http://www02.abb.com'
    }
    soPageURL = new String(window.location.href);
    i1 = soPageURL.indexOf('http://');
    if (i1 >= 0) 
    {
        soPageURL = escape(soPageURL.substring(7, soPageURL.length));
    }

    contactus = window.open(server + contacturl, "contactus","width=578,height=600,toolbar=0,directories=0,menubar=0,status=0,resizable=0,location=0,scrollbars=1,copyhistory=0,alwaysRaised=1");
    contactus.focus();
}

/*********** Fontsize functions ************/
function setFontsize(size, useCookie)
{
    if (!size || size == '' || size == 'null')
    {
        size = 'normal';
    }
    setSelectedFontSize(size);
	
	if (size == 'normal')
    	$('body').css('font-size', ''); // 75%
    else if (size == 'large')
    	$('body').css('font-size', '90%');
    else if (size == 'huge')
    	$('body').css('font-size', '100%');
	
	if (useCookie == true)
	{
	    setCookie('FONTSIZE', size, null, '/');
	}
	$("body").trigger("fontResized");
}
function setSelectedFontSize(size) {
    if (document.getElementById('fontSize_normal') == null) {
        setTimeout("setSelectedFontSize('" + size +"')", 500);
        return;
    }
    setFontSizeLink('normal', size);
    setFontSizeLink('large', size);
    setFontSizeLink('huge', size);
}

function setFontSizeLink(size, value) {
    if (size == value) {
        $("#fontSize_" + size).addClass("selected");
    } else {
        $("#fontSize_" + size).removeClass("selected");
    }
}

$(document).ready(function(){setFontsize(getCookie('FONTSIZE'),false);});

/*********** Toolbox ************/

function validateRateThisPage(rateFieldId, errorMessage)
{
    var objRateField = document.getElementById(rateFieldId);
    if (objRateField != null && objRateField.value == '')
    {
        alert(errorMessage);
        return false;
    }
    return true;
}

function setRateThisPageValue(rateFieldId, objCurrentElement, value)
{
    var objRateField = document.getElementById(rateFieldId);
    if ('' + objRateField != 'undefined' && '' + objCurrentElement != 'undefined')
    {
        objRateField.value = value;    
        var buttonCollection = objCurrentElement.parentNode.getElementsByTagName("li");
        for (var i = 0; i < buttonCollection.length; i++)
        {        
            var objButton = buttonCollection[i];
            
            setElementNamedItem(objButton, "class", "");
        }            
    }

    setElementNamedItem(objCurrentElement, "class", "selected");
    var currentElementId = objCurrentElement.id;
    if (value > 1 && objCurrentElement.id.length > 1 && objCurrentElement.id.indexOf(value) != -1)
    {
        var baseElementId = objCurrentElement.id.substring(0, objCurrentElement.id.length-1);
        
        for (var i = 1; i < value; i++)
        {
            var elementId = baseElementId + i;
            var theElement = document.getElementById(elementId);
            if ('' + theElement != 'undefined')
            {
                setElementNamedItem(theElement, "class", "selected");
            }
        }
    }
}

function setElementNamedItem(objElement, strAttributeName, strValue)
{
    var namedItem = document.createAttribute(strAttributeName);
    namedItem.value = strValue;
    objElement.attributes.setNamedItem(namedItem);
}

function openCategoryInMenu(listId, item)
{
    var item = document.getElementById(listId);
    var link = document.getElementById('link_' + listId);
    var list = document.getElementById('cat_' + listId);
    if (list)
    {
        if (list.style.display == 'none')
        {
            list.style.display = 'block';
            if (item) { item.className = 'open'; }
            if (link) { link.className = 'open'; }
        }
        else
        {
            list.style.display = 'none';
            if (item) { item.className = 'closed'; }
            if (link) { link.className = 'closed'; }
        }
    }
}

function hideValidatorsMessages(sender, idPanel) {
    var panel = document.getElementById(idPanel);
    if (panel != null) {
        if (panel.style.display == "") //when visible
        {
             panel.style.display = "none";
        }
    }
}

function toggleUpdateButtonUser(updateButton, initValues, controlIds) {
    isTheSame = true;

    var newGivenNameValue = document.getElementById(controlIds[0]).value;
    var newMiddleNameValue = document.getElementById(controlIds[1]).value;
    var newSurnameValue = document.getElementById(controlIds[2]).value;
    var newCompanyValue = document.getElementById(controlIds[3]).value;
    var countryList = document.getElementById(controlIds[4]);
    var selectedCountryIndex = countryList.selectedIndex;
    var newCountryValue = countryList.options[selectedCountryIndex].value;
    var languageList = document.getElementById(controlIds[5]);
    var selectedLanguageIndex = languageList.selectedIndex;
    var newLanguageValue = languageList.options[selectedLanguageIndex].value;
    var newPhoneNumberValue = document.getElementById(controlIds[6]).value;

    if (initValues[0] != newGivenNameValue) {
        isTheSame = false;
    }
    if (initValues[1] != newMiddleNameValue) {
        isTheSame = false;
    }
    if (initValues[2] != newSurnameValue) {
        isTheSame = false;
    }
    if (initValues[3] != newCompanyValue) {
        isTheSame = false;
    }
    if (initValues[4] != newCountryValue) {
        isTheSame = false;
    }
    if (initValues[5] != newLanguageValue) {
        isTheSame = false;
    }
    if (initValues[6] != newPhoneNumberValue) {
        isTheSame = false;
    }
    document.getElementById(updateButton).disabled = isTheSame;
}

function encodeNoteField(fieldNote)
{
    var fieldNoteValue = $('#' + fieldNote).val();

    fieldNoteValue = fieldNoteValue.replace(/</gi, "&lt;");
    fieldNoteValue = fieldNoteValue.replace(/>/gi, "&gt;");

    $('#' + fieldNote).val(fieldNoteValue);
}

function IsCheckboxChecked(checkbox)
{
    if (typeof(checkbox) == "undefined")
    {
        return false;
    }
    else
    {
        return checkbox.checked;
    }
}

jQuery.fn.jumpMenu = function() {
    init(this);
    return this;

    function init(elements) {
        elements.bind("change", handleChange);
    }

    function handleChange(event) {
        var target = jQuery(event.target);
        var url = target.val();
        if (url != null && url != "") {
            location.href = url;
        }
    }
}

jQuery.fn.defaultText = function (text) {
    if (text == undefined || text == null || text == "")
        return;

    try {
        if (this.val() == null || this.val() == "" || this.val() == text) {
            this.val(text);
            this.css('color', '#7f7f7f');
            this.attr('hasdefaulttext', 'true');
        }

        this.focus(function () {
            var o = $(this);
            if (o.attr('hasdefaulttext') === 'true') {
                o.val('');
                o.css('color', '#000');
                o.attr('hasdefaulttext', 'false');
            }
        });
        this.blur(function () {
            var o = $(this);
            if (o.val() === '') {
                o.val(text);
                o.css('color', '#7f7f7f');
                o.attr('hasdefaulttext', 'true');
            }
        });
    }
    catch (err) {
        /* Ignore error on very old IE6 version */
    }
}

/* Set default text to input fields */
$(document).ready(function() {
    $("input.defaultInputValue").each(function(){
        var text = $(this).attr('title');
        $(this).defaultText(text);
    })
});

/* Fix hover effects for IE6 */
$(document).ready(function() {
    if (!/MSIE (5|6)/.test(navigator.userAgent))
        return;

    $('.button:disabled,.buttonSmall:disabled,.buttonTiny:disabled').addClass('buttonDisabled');

    $("input").each(function(){
        var className = this.className;
        var type = this.type;
        
        var isButtonClass = (className.substring(0, 6) == "button")
        if (isButtonClass)
        {
            var isButtonType = ((type == "button") || (type == "submit"))
            if (isButtonType)
            {
                $(this).hover(function() { $(this).addClass('buttonHover'); }, 
                              function() { $(this).removeClass('buttonHover'); })
            }
        }
    })

    $('#toolbox li.closed a.toolHeading').hover(function() { $(this).addClass('toolHeadingHover'); }, 
                                                function() { $(this).removeClass('toolHeadingHover'); });

    $('#toolbox li.open a.toolHeading').hover(function() { $(this).addClass('toolHeadingHover'); }, 
                                              function() { $(this).removeClass('toolHeadingHover'); });
});

/* Add alternating stylesheet to tables */
$(document).ready(function() {
    $('table.standard').each(function(){
        $('tr:odd', this).addClass('altRow');
        $('tr:not(:has(td))', this).addClass('headerRow');
    }).removeAttr("border");
});


jQuery.fn.abbToolsItem = function() {
    var mother = this;
    var heading = this.find('.toolHeading');
    var content = this.find('.toolBoxCollapsiblePanel');
    content.hide();
    heading.bind('click', function() {
        toggleContent();
    });
    this.find('.closePanel:not([href])').attr('href', '#');
    this.find('.closePanel').bind('click', function() {
        toggleContent();
    });
    $.extend(this, {
        'toggleContent': toggleContent,
        'showContent': showContent,
        'hideContent': hideContent
    });
    return this;

    function toggleContent() {
        content.toggle();
        mother.toggleClass('closed');
        mother.toggleClass('open');
    }

    function showContent() {
        content.show();
        mother.removeClass('closed');
        mother.addClass('open');
    }

    function hideContent() {
        content.hide();
        mother.removeClass('open');
        mother.addClass('closed');
    }
}

jQuery.fn.emailThisPage = function (shareToolItem, emailToolItem) {
    var mother = this;
    var pageMailedStatus = this.find('#pageMailedStatus');
    if (pageMailedStatus.length == 1) {
        shareToolItem.toggleContent();
        emailToolItem.showContent();
        if (pageMailedStatus.val().toLowerCase() == 'false') {
            mother.find('>div:first').show().nextAll().hide();
        }
    }
    return this;
}

jQuery.fn.sendAnotherEmail = function (shareToolItem, emailToolItem) {
    this.click(function () {
        var pageMailedStatus = emailToolItem.find('#pageMailedStatus');
        if (pageMailedStatus.length == 1) {
            emailToolItem.find('#emailThisPage').find('>div:first').hide().nextAll().show();
        }
    });
    return this;
}

jQuery.fn.sendEmailClose = function (shareToolItem, emailToolItem) {
    this.click(function () {
        var pageMailedStatus = emailToolItem.find('#pageMailedStatus');
        if (pageMailedStatus.length == 1) {
            shareToolItem.toggleContent();
            emailToolItem.toggleContent();
            emailToolItem.find('#emailThisPage').find('>div:first').hide().nextAll().show();
        }
    });
    return this;
}

jQuery.fn.rateThisPage = function(toolItem)
{
    var mother = this;    
    this.find('#hiddenRateButtons').show();
    var isClicked = this.find('#rateThisPageClicked');
    if (isClicked.length == 1)
    {
        toolItem.showContent();
        $.timer(5000, function (timer)
        {
            toolItem.toggleContent();
            timer.stop();
	    });
    }
    return this;
}

jQuery.fn.shareThisPage = function (shareToolItem, emailToolItem) {
    this.find("a.email").bind("click", handleEmailClicked);
    this.find("a.print").bind("click", handlePrintClicked);
    shareToolItem.find(".toolHeading").bind("click", handleCollapseClicked);

    function handleEmailClicked(event) {
        event.preventDefault();
        emailToolItem.toggleContent();
    }
    function handlePrintClicked(event) {
        event.preventDefault();
        window.print();
    }
    function handleCollapseClicked(event) {
        emailToolItem.hideContent();
    }
}


function fireButtonClickIfEnter(event, target)
{
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            var defaultButton = document.getElementById(target);

            if (defaultButton && typeof(defaultButton.click) != "undefined") {
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation)
                    event.stopPropagation();
                return false;
            }
        }
    }    
    return true;
}


function validateSubFields(id, emailRegExp)
{
    var valid = true;

    $('#' + id + ' .required').each(function () {
        valid = validateField(this, emailRegExp) && valid;
    });
    return valid;
}

function validateField(field, emailRegExp)
{
    var valid = true;    
    if ($(field).hasClass("required"))
    {
        if (field.value == null || field.value == "")
        {
            valid = false;
            $("#" + field.id + "_error").show();
        }
        else
        {
            $("#" + field.id + "_error").hide();
        }
    }

    if (valid && emailRegExp != null && emailRegExp != "" && $(field).hasClass("email"))
    {
        if (valid && (field.value.search(emailRegExp) == -1))
        {
            valid = false;
            $("#" + field.id + "_error").show();
        }
        else
        {
            $("#" + field.id + "_error").hide();
        }
    }

    return valid;
}

// Set the width of image caption text
$(document).ready(function() {
    $(".contentImage .caption").each(function() {
        var imgForCaption = $(this).prev("img");
        if (imgForCaption != null) {
            var captionWidth = imgForCaption.width() - 8;
            $(this).css("width", captionWidth + "px");
        }
    });
});

// Custom Select element
; (function($) {
    $.fn.extend({
        getByteLength: function(strIN) {
            var i, cnt = 0;

            for (i = 0; i < strIN.length; i++) {
                if (escape(strIN.charAt(i)).length >= 4) cnt += 2;
                else cnt++;
            }

            return cnt;
        }
    });

    $.fn.extend({
        getIndexByByte: function(strIN, limit) {
            var i, cnt = 0;

            for (i = 0; i < strIN.length; i++) {
                if (escape(strIN.charAt(i)).length >= 4) cnt += 2;
                else cnt++;

                if (cnt > limit) {
                    return [true, i];
                }
            }

            return false;
        }
    });

    $.fn.extend({
        finalselect: function(options) {
            var settings =
	    {
	        id: null,
	        animalSpeed: 100,
	        selectWidth: "190px",
	        selectImage: "image/select.png",
	        selectText: "My friend",
	        zIndex: 0,
	        viewHeight: "100px",
	        viewWidth: "300px",
	        viewMouseoverColor: "#cfdfff", //#dcdcdc
	        viewTop: "28px", //top,bottom
	        viewLeft: " -1px", //left,right
	        elementChanged: null
	    };

            if (typeof (options) != 'undefined') {
                jQuery.extend(settings, options);
            }
            var tmp = '<div id="' + settings.id + '-select" style="cursor:default;font-size:12px;z-index:' + settings.zIndex + ';border: solid 0px #999; padding: 0px; width: 180px; position: relative;">'
            tmp += '<div id="' + settings.id + '-Text" style="background: url(' + settings.selectImage + ') no-repeat 0 0; width: ' + settings.selectWidth + '; height: 21px; color: black; padding: 0  0 0 5px;">';
            tmp += '<div class="textshow" style="padding: 3px 0 0 0;">' + settings.selectText + '</div><div class="valueshow" style="display:none;"></div></div><div style=" color:#bbb; text-align:right;font-size:9px; display:none;">powered by <a href="http://finalevil.blogspot.com" style="text-decoration:none;">finalevil</a></div><div id="' + settings.id + '-selectshow" style="overflow-y:auto; overflow-x:hidden; height:' + settings.viewHeight + ';width:' + settings.viewWidth + '; display:none; position: absolute; left:' + settings.viewLeft + '; top:' + settings.viewTop + '; border: solid 1px #999; background: white;"></div></div>';

            var _handler = function() {
                $(this).html(tmp);
                bindArrowClick();
                bindSelectMouseover();
                bindSelectMouseleave();
            };

            var bindArrowClick = function() {
                var tmp = $('#' + settings.id + '-Text');
                $("#" + settings.id + '-Text').bind("click", function(e) {
                    var obj = $('#' + settings.id + '-selectshow');
                    if (obj.css('display') == 'none') {
                        // obj.slide();                
                        obj.slideDown(settings.animalSpeed, function() {
                            obj.show();
                            obj.css('overflow', 'auto');
                            obj.css('overflow-x', 'hidden');
                        });
                    }
                    else {
                        obj.slideUp(settings.animalSpeed, function() {
                            obj.hide();
                        });
                    }

                });
            };

            var bindItemMouseover = function() {

                var inx = 0;

                while ($(".selectitem", $("#" + settings.id + "-selectshow")).get(inx) != null) {
                    var item = $(".selectitem", $("#" + settings.id + "-selectshow")).get(inx);

                    if (inx % 2 == 0) {
                        $(item).css('background-color', '#eeeeee');
                    } else {
                        $(item).css('background-color', '#ffffff');
                    }

                    $(item).bind("mouseover", function(e) {
                        $(this).css('background-color', settings.viewMouseoverColor);
                    });

                    $(item).bind("mouseout", { index: inx }, function(e) {
                        if (e.data.index % 2 == 0) {
                            $(this).css('background-color', '#eeeeee');
                        } else {
                            $(this).css('background-color', '#ffffff');
                        }
                    });

                    $(item).bind("click", function(e) {

                        var tmpstr = $(".thistext", $(this)).html();
                        var arr = $().getIndexByByte(tmpstr, 16);
                        if (arr[0] == true)
                            tmpstr = tmpstr.substring(0, arr[1]) + '...';

                        $(".textshow", $("#" + settings.id + "-Text")).html(tmpstr);
                        document.getElementById(settings.id + '-selectshow').style.display = "none";

                        $(".valueshow", $("#" + settings.id + "-Text")).html($(".selectvalue", $(this)).html());
                        if (settings.elementChanged != null) {
                            settings.elementChanged($(this).find(".selectvalue").html());
                        }
                    });

                    inx++;
                }

            }

            var bindSelectMouseover = function() {
                $('#' + settings.id + '-Text').bind("mouseover", function() {
                    $('#' + settings.id + '-Text').css("background-position", "0 -21px");
                });
            }

            var bindSelectMouseleave = function() {
                $('#' + settings.id + '-Text').bind("mouseout", function() {
                    $('#' + settings.id + '-Text').css("background-position", "0 0px");
                });
            }

            this.setViewTop = function(top) {
                $('#' + settings.id + '-selectshow').css('top', top + 'px');
            }

            this.setViewLeft = function(left) {
                $('#' + settings.id + '-selectshow').css('left', left + 'px');
            }

            this.getLength = function() {
                return $('.selectitem', $('#' + settings.id + '-selectshow')).length;
            }
            this.addItem = function(itemtext, itemvalue) {

            var itemhtml = '<div class="selectitem" style="cursor:default; padding: 4px;"><div class="selecttext" style="width: 100%; text-align: left;">' + itemtext
            + '</div><div class="selectvalue" style=" display:none;">' + itemvalue + '</div></div><div class="selectborder"><div>';

                $("#" + settings.id + '-selectshow').html($("#" + settings.id + '-selectshow').html() + itemhtml);

                bindItemMouseover();
            };

            this.selectItem = function(itemvalue) {
                $("#" + settings.id + '-selectshow').find(".selectitem").find(".selectvalue:contains('" + itemvalue + "')").parent().click();
            }

            this.removeItem = function(index) {
                if ($('.selectitem', $('#' + settings.id + '-selectshow')).length > index)
                    $($('.selectitem', $('#' + settings.id + '-selectshow')).get(index)).remove();
                if ($('.selectborder', $('#' + settings.id + '-selectshow')).length > index)
                    $($('.selectborder', $('#' + settings.id + '-selectshow')).get(index)).remove();
            }

            this.getValue = function() {
                return $('.valueshow', $('#' + settings.id + '-Text')).html();
            }

            this.getText = function() {
                return $('.textshow', $('#' + settings.id + '-Text')).html();
            }


            return this.each(_handler);
        }

    });

})(jQuery);
//End of Custom Select Element

