// wevi functions
function weviCtrlSetState(id, enabled) {
    $('#' + id).attr('class', (enabled ? 'wevictrl' : 'wevictrl_disabled'));
}

// functions for the wevi textbox
function weviTextboxInit(id) {
    var elem = $('#' + id + '_value');
    elem.bind('focus', weviTextboxFocus).bind('blur', weviTextboxBlur);
}

function weviTextboxDeactivateFocusBlur(id) {
    var elem = $('#' + id + '_value');
    elem.unbind('focus', weviTextboxFocus).unbind('blur', weviTextboxBlur);
}

function weviTextboxFocus() {
    weviDropdownReset(null);
    this.parentNode.parentNode.className = 'wevictrl_focus wevictrl_tbfocus';
    if (this.value == this.defaultText) {
        $(this).val('').find('input').addClass('defaulttext');
    }
}

function weviTextboxBlur() {
    this.parentNode.parentNode.className = 'wevictrl wevictrl_tb';
    if (this.defaultText && this.value.length == 0) {
        $(this).val(this.defaultText).find('input').removeClass('defaulttext');
    }
}

function weviTextboxEnabled(id, enabled) {
    $('#' + id).attr('class', (enabled ? 'wevictrl wevictrl_tb' : 'wevictrl_disabled wevictrl_tbdisabled'));
    $('#' + id + '_value').attr('disabled', !enabled);
}

// functions for the weviDropdown control
var m_dropdowns = new Array();
function weviDropdownReset(id) {
    // hide all open dropdowns
    var label;
    for (var i = 0; i < m_dropdowns.length; i++) {
        if (m_dropdowns[i] != id) {
            if (!$('#' + m_dropdowns[i]).hasClass('wevictrl_disabled') &&
				!$('#' + m_dropdowns[i]).hasClass('wevictrl_error')) {
                $('#' + m_dropdowns[i]).attr('class', 'wevictrl');
            }
        }

        label = $('#' + m_dropdowns[i]).prev();
        if (label != null) {
            if (label.hasClass('label-active')) label.removeClass('label-active');
        }
    }
    if (id == null) $(document).unbind('keydown');
}

function weviDropdownPreSelectItem(id, firstCall) {
    if (firstCall) {
        if (m_dropdowns.length == 0) {
            $('body').bind('click', function(event) {
                $(event.target).trigger('vcclose');
                var id = event.target.parentNode.id;
                for (var i = 0; i < m_dropdowns.length; i++)
                    if (m_dropdowns[i] == id) return;
                weviDropdownReset(null);
                event.stopPropagation();
            });
        }
        m_dropdowns.push(id);
    }
    var selLine = $('#' + id + '>div.c');
    var value = $('#' + id + '_value').val();
    var items = $('#' + id + '_items a');
    items.each(function(n) {
        if (this.attributes['value'].value == value) {
            selLine.html(this.innerHTML);
            $(this).addClass('selected');
        };
        this.href = "javascript:weviDropdownSelectItem('" + id + "','" + n + "',true)";
    });
    if (firstCall) {
        var elem = $('#' + id + '_items');
        var dropdownItems = elem.attr('ddi');
        elem.height(Math.min(items.length, parseInt(dropdownItems)) * 15);
        elem.css('top', selLine.position().top + selLine.height() + 1);
        elem.css('left', selLine.position().left - 5);
        elem.bind('mousemove', function(e) { items.removeClass('selected'); });
    }
}



function weviDropdownShowItems(id) {
    weviDropdownReset(id);

    var elem = $('#' + id);
    if (elem.attr('class') == 'wevictrl_disabled') return;
    var hasFocus = (elem.attr('class') == 'wevictrl');
    elem.attr('class', (hasFocus ? 'wevictrl_focus' : 'wevictrl'));
    // workaround for IE6 - force popup redraw (try to remove)
    if (navigator.appVersion.indexOf("MSIE 6.0") != -1 || navigator.appVersion.indexOf("MSIE 7") != -1) {
        var popup = document.getElementById(id).lastChild;
        popup.style.borderWidth = "1px";
        var parentElm = popup.parentNode;
        parentElm.removeChild(popup);
        for (i = 0; i < popup.childNodes.length; i++) {
            if (popup.childNodes.style)
                popup.childNodes[i].style.width = (parseInt(popup.style.width) - 22) + "px";
        }
        parentElm.appendChild(popup);
    }

    weviDropdownPreSelectItem(id, true);

    if (hasFocus) {
        $('#' + id + ' a.selected').focus();
        $(document).bind('keydown', function(e) {
            var handled = false;
            if (e.keyCode == 38 || e.keyCode == 40) {
                var items = $('#' + id + '_items a');
                var selItem = $('#' + id + '_items a.selected');
                var selIndex = items.index(selItem);
                if (e.keyCode == 38 && selIndex > 0) weviDropdownSelectItem(id, selIndex - 1, false);
                if (e.keyCode == 40 && selIndex < items.length - 1) weviDropdownSelectItem(id, selIndex + 1, false);
                handled = true;
            }
            if (e.keyCode == 13) {
                weviDropdownReset(null);
                handled = true;
            }
            if (!handled) {
                $('#' + id + '_items a').each(function(index) {
                    if (handled == false && this.innerHTML.toUpperCase().charCodeAt(0) == e.keyCode) {
                        weviDropdownSelectItem(id, index, false);
                        $(this).focus();
                        handled = true;
                    }
                });
            }
            e.stopPropagation();
            return false;
        });
    }

    var label = elem.prev();
    if (label != null) {
        if (hasFocus) {
            label.addClass('label-active');
        }
    }
}

function weviDropdownSelectItem(id, index, unbind) {
    var selLine = $('#' + id + ' .c');
    var changed = false;
    $('#' + id + '_items a')
			.each(function() { $(this).removeClass('selected'); })
			.each(function(n) {
			    if (index == n) {
			        selLine.html(this.innerHTML);
			        $(this).addClass('selected');
			        var hd = $('#' + id + '_value');
			        if (hd.attr('value') != this.attributes['value'].value) {
			            hd.attr('value', this.attributes['value'].value);
			            changed = true;
			        }
			    }
			});
    if (unbind) $(document).unbind('keydown');
    if (changed) {
        var elem = $('#' + id);
        if (elem.attr('onchanged')) eval(elem.attr('onchanged'));
    }
}

function weviDropdownFindIndexByValue(id, value) {
    var index = -1;
    $('#' + id + '_items a').each(function(n) {
        if (this.attributes['value'].value == value) index = n;
    });
    return index;
}


// bubble (source: http://jqueryfordesigners.com/coda-popup-bubbles/)
weviWireInfoBubbleElements = function() {
    $('.bubble-info').each(function() {
        // options
        var distance = 0;
        var time = 250;
        var hideDelay = 150;
        var hideDelayTimer = null;
        var showDelay = 150;
        var showDelayTimer = null;

        // tracker
        var beingShown = false;
        var shown = false;
        var trigger = $('.trigger', this);
        var popup = $('.bubble-popup', this).css('opacity', 0);

        // set the close event
        if ($("div > div:eq(0) > img", this).length > 0) {
            $("div > div:eq(0) > img", this).click(function() {
                $(this).parent().parent().hide();
            });
        }

        if ($("div >  div:eq(0) > div[class=t] > img", this).length > 0) {
            $("div > div:eq(0) > div[class=t] > img", this).click(function() {
                $(this).parent().parent().parent().hide();
            });
        }

        // set the mouseover and mouseout on both element
        $([trigger.get(0), popup.get(0)]).mouseover(function() {
            // stops the hide event if we move from the trigger to the popup element
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            showDelayTimer = setTimeout(function() {
                // don't trigger the animation again if we're being shown, or already visible
                if (beingShown || shown) {
                    return;
                } else {

                    beingShown = true;
                    var popupTop = 0;
                    var popupLeft = 0;
                    var popupClass = popup.prevObject[0].className;

                    if (popupClass.indexOf("bubble-left") > 0) {
                        popupTop = -36;
                        popupLeft = -popup.width();
                    }
                    else if (popupClass.indexOf("bubble-right") > 0) {
                        popupTop = -36;
                        popupLeft = 11;
                    }
                    else {
                        popupTop = -(popup.height() + 4);
                        popupLeft = -46;
                    }


                    // reset position of popup box
                    popup.css({
                        top: popupTop, // dynamic height
                        left: popupLeft,
                        display: 'block' // brings the popup back in to view
                    })

                    // (we're using chaining on the popup) now animate it's opacity and position
				        .animate({
				            top: '-=' + distance + 'px',
				            opacity: 1
				        }, time, 'swing', function() {
				            // once the animation is complete, set the tracker variables
				            beingShown = false;
				            shown = true;
				        });
                }
            }, showDelay);
        }).mouseout(function() {
            // reset the timer if we get fired again - avoids double animations
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            if (showDelayTimer) clearTimeout(showDelayTimer);

            // store the timer so that it can be cleared in the mouseover if required
            hideDelayTimer = setTimeout(function() {
                hideDelayTimer = null;
                popup.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function() {
                    // once the animate is complete, set the tracker variables
                    shown = false;
                    // hide the popup entirely after the effect (opacity alone doesn't do the job)
                    popup.css('display', 'none');
                });
            }, hideDelay);
        });
    });
}

$(document).ready(weviWireInfoBubbleElements);

// make model selection
var m_includeModelLine = true;
function makeModelSelect(makeListId, modelListId, versionId, includeModelLine) {
    m_includeModelLine = includeModelLine;
    var oldModel = $('#' + modelListId + '_value').val();
    if (makeChanged(makeListId, modelListId, versionId) > 0 && oldModel != 0) {
        $('#' + modelListId + '_value').val(oldModel);
        weviDropdownPreSelectItem(modelListId, false);
        modelChanged(modelListId, versionId);
    }
}

function makeChanged(makeListId, modelListId, versionId) {
    var makeList = $('#' + makeListId);
    var modelList = $('#' + modelListId);
    var modelListItems = $('#' + modelListId + '_items');
    var modelVal = $('#' + modelListId + '_value');
    $('#' + modelListId + '_items > a:gt(0)').remove();

    var index = weviDropdownFindIndexByValue(makeListId, parseInt($('#' + makeListId + '_value').attr('value')));
    if (index > 0) {
        var allModels = arrModels[index].split(';');
        for (var i = 0; i < allModels.length; i++) {
            var splited = allModels[i].split(',');
            modelListItems.append('<a value="' + splited[0] + '" selected="0">' + splited[1] + '</a>');
        }
        var model = $('#' + modelListId + '_items > a:eq(1)');
        if (allModels.length == 1) modelVal.attr('value', model.attr('value'));
        $('#' + modelListId + '_value').attr('value', (allModels.length == 1 ? $('#' + modelListId + '_items > a:eq(1)').attr('value') : '0'));
        modelListItems.height(Math.min(allModels.length, 6) * 15);
    }
    else {
        weviDropdownSelectItem(modelListId, 0, true);
    }
    weviCtrlSetState(modelListId, index > 0);
    var pointsDiv = makeList.next();
    if (pointsDiv != null) {
        pointsDiv.attr('class', (index > 0 ? 'points-blue' : 'points-grey'));
    }
    weviDropdownPreSelectItem(modelListId, false);
    if (versionId) modelChanged(modelListId, versionId);
    return index;
}

function modelChanged(modelListId, versionId) {
    var val = parseInt($('#' + modelListId + '_value').val());
    if (versionId) weviTextboxEnabled(versionId, val > 0);
    return weviDropdownFindIndexByValue(modelListId, val);
}

// slider
function weviSetSliderValue(event, ui) {
    $('#' + ui.handle.parentNode.id + '_val0').attr('value', ui.values[0]);
    $('#' + ui.handle.parentNode.id + '_val1').attr('value', ui.values[1]);
}

function toggleSlider(parentClass, disabledClass, sliderMarkerCss) {
    var $slider = $('#' + parentClass);
    var $sliderControl = $('.' + sliderMarkerCss);
    if (!$slider.hasClass(disabledClass)) {
        $slider.addClass(disabledClass);
        $sliderControl.slider('disable');
    }
    else {
        $slider.removeClass(disabledClass);
        $sliderControl.slider('enable');
    }
}

// horizontal tab
$(function() {
    $('.tabs div span.text').bind('click',
    function activateTab(event) {
        var pn = $(event.target.parentNode);
        var ctrl = pn[0].parentNode;
        if (ctrl.attributes.beforechanged) {
            if (!eval(ctrl.attributes.beforechanged.value)) return;
        }
        if (pn.hasClass('active')) return;
        $('.tabs div').removeClass('active');
        pn.addClass('active');
        $('#' + ctrl.id + '_value').val(pn.attr('value'));
        if (ctrl.attributes.afterchanged) eval(ctrl.attributes.afterchanged.value);
    }
  )
});

// checkboxes
$(function() {
    $('span.wevi_check').bind('mouseover', function(e) {
        $(e.currentTarget).addClass('wevi_check_focus');
    }).bind('mouseout', function(e) {
        $(e.currentTarget).removeClass('wevi_check_focus');
    }).bind('click', function(e) {
        var elem = $(e.currentTarget);
        elem.toggleClass('wevi_check_checked');
        var state = elem.hasClass('wevi_check_checked') ? 'true' : 'false';
        $('#' + this.id + '_val').val(state);
        var cc = elem[0].attributes.oncheckchanged;
        if (cc && cc.value.length > 0) eval(cc.value + '(' + e.id + ',' + state + ')');
        var ap = elem[0].attributes.autopostback;
        if (ap && ap.value.toLowerCase() == 'true') __doPostBack(e.currentTarget.id, '');
        $('body').focus();
    });
});

// radiobuttons
$(function() {
    $('span.wevi_radio').bind('mouseover', function(e) {
        $(e.currentTarget).addClass('wevi_radio_focus');
    }).bind('mouseout', function(e) {
        $(e.currentTarget).removeClass('wevi_radio_focus');
    }).bind('click', function(e) {
        var elem = $(e.currentTarget);
        elem.addClass('wevi_radio_checked');
        $('#' + this.id + '_val').val('true');
        var groupname = elem[0].attributes.name ? elem[0].attributes.name.value : '';
        if (groupname.length > 0) {
            $('span.wevi_radio[name=' + groupname + ']').each(function() {
                if (this !== elem[0]) {
                    $(this).removeClass('wevi_radio_checked');
                    $('#' + this.id + '_val').val('false');
                }
            });
        }
        var cc = elem[0].attributes.oncheckchanged;
        if (cc && cc.value.length > 0) eval(cc.value + '(' + e.id + ',' + state + ')');
        var ap = elem[0].attributes.autopostback;
        if (ap && ap.value.toLowerCase() == 'true') __doPostBack(e.currentTarget.id, '');
        $('body').focus();
    });
});

function textAreaFocus(e) {
    $(e.target.parentNode.parentNode.parentNode.parentNode.parentNode).addClass('wevi_tb_multiline_focus');
}

function textAreaBlur(e) {
    $(e.target.parentNode.parentNode.parentNode.parentNode.parentNode).removeClass('wevi_tb_multiline_focus');
}

$(function() {
    // multiline textbox
    $('div.wevi_tb_multiline textarea').bind('focus', textAreaFocus).bind('blur', textAreaBlur);

    // primary action button
    $('div.primary-action').bind('mouseover', function(e) {
        $(e.currentTarget).addClass('primary-action-focus');
    }).bind('mouseout', function(e) {
        $(e.currentTarget).removeClass('primary-action-focus');
    });
    // additional action button
    $('div.additional-action').bind('mouseover', function(e) {
        $(e.currentTarget).addClass('additional-action-focus');
    }).bind('mouseout', function(e) {
        $(e.currentTarget).removeClass('additional-action-focus');
    });
    // additional action back button
    $('div.additional-action-back').bind('mouseover', function(e) {
        $(e.currentTarget).addClass('additional-action-back-focus');
    }).bind('mouseout', function(e) {
        $(e.currentTarget).removeClass('additional-action-back-focus');
    });
});

// mark control as error / correct
function markWeviTextBoxError(weviTextBoxId) {
    $('#' + weviTextBoxId).addClass('wevictrl_tb_error').removeClass('wevictrl_tb').addClass('wevictrl_error').removeClass('wevictrl');
    $('#' + weviTextBoxId + '_value').removeClass('defaulttext');
    //$('#' + weviTextBoxId + '_value').attr('value', '');
    $('#' + weviTextBoxId).bind('focus', function() { markWeviTextBoxCorrect(weviTextBoxId); });
    //weviTextboxDeactivateFocusBlur(weviTextBoxId);
}

function markWeviTextBoxCorrect(weviTextBoxId) {
    weviTextboxInit(weviTextBoxId);
    $('#' + weviTextBoxId).addClass('wevictrl_tb').removeClass('wevictrl_tb_error').addClass('wevictrl').removeClass('wevictrl_error');
    //var obj = $('#' + weviTextBoxId + '_value');
    //if(obj.val() == obj.defaultText) {
    //    obj.addClass('defaulttext');
    //}
}

function markDropDownError(id) {
    $('#' + id).addClass('wevictrl_error').removeClass('wevictrl');
}

function markDropDownCorrect(id) {
    $('#' + id).addClass('wevictrl').removeClass('wevictrl_error');
}

function markTextAreaError(id) {
    //$('#' + id).unbind('focus', textAreaFocus).unbind('blur', textAreaBlur);
    var el = document.getElementById(id);
    if (el && el.parentNode && el.parentNode.parentNode && el.parentNode.parentNode.parentNode && el.parentNode.parentNode.parentNode.parentNode && el.parentNode.parentNode.parentNode.parentNode.parentNode && el.parentNode.parentNode.parentNode.parentNode.parentNode.className.indexOf('wevi_tb_multiline') > -1) {
        //if(el && el.parentNode && el.parentNode.parentNode && el.parentNode.parentNode.parentNode && el.parentNode.parentNode.parentNode.className.indexOf('wevi_tb_multiline') > -1) {

        el = el.parentNode.parentNode.parentNode.parentNode.parentNode;
        el.className = el.className.replace('wevi_tb_multiline_error', '').replace('wevi_tb_multiline', '');
        el.className += ' wevi_tb_multiline_error ';
    }
    $('#' + id).bind('focus', function() { markTextAreaCorrect(id); });

}

function markTextAreaCorrect(id) {
    var el = document.getElementById(id);
    if (el && el.parentNode && el.parentNode.parentNode && el.parentNode.parentNode.parentNode && el.parentNode.parentNode.parentNode.parentNode && el.parentNode.parentNode.parentNode.parentNode.parentNode) {
        el = el.parentNode.parentNode.parentNode.parentNode.parentNode;
        el.className = el.className.replace('wevi_tb_multiline_error', 'wevi_tb_multiline');
    }
    //$('#' + id).bind('focus', textAreaFocus).bind('blur', textAreaBlur);
}
