﻿/* This file contains utility functions which are generally useful in this project*/
var DFSexyDefaults = {
    validator : validateHelper
};

var SHIFT_DOWN = false;
var CTRL_DOWN = false;
var ALT_DOWN = false;
$(document).ready( function() {
    $(document).keydown( function(kev) {
        if( kev.keyCode == 16 ) { SHIFT_DOWN = true; } else
        if( kev.keyCode == 17 ) { CTRL_DOWN = true; } else 
        if( kev.keyCode == 18 ) { ALT_DOWN = true }
    }).keyup( function(kev) {
        if( kev.keyCode == 16 ) { SHIFT_DOWN = false; } else
        if( kev.keyCode == 17 ) { CTRL_DOWN = false; } else 
        if( kev.keyCode == 18 ) { ALT_DOWN = false }
    });
});
var weekdays = ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

function bindMethod( object, method ) {
	return function () {
		return method.apply( object, arguments );
	}
}

function createDiv() { return $(document.createElement( "div" ) ); }

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function arrContains( arr, element ) {
    for( var i = 0; i < arr.length; i++ ) {
        if( arr[i] == element ){
            return i;
        }
    }
    
    return -1;
}

function makeSexy( context, options ) {
    if( context ) {
        $("input[type=text]:not(.fugly)", context ).sexy( DFSexyDefaults );
        $("input[type=password]:not(.fugly)", context ).sexy( DFSexyDefaults );
        $("select:not(.fugly)", context ).sexy( DFSexyDefaults ); 
        $("div.input-sexyList", context ).sexyList();
        $("div.sexyToolMenu", context).sexyToolMenu();
        /*$.each($("fieldset:not(.fugly) legend", context), function() {
            $(this).replaceWith($(document.createElement("DIV")).attr("class", "legend").html($(this).html()));
        });*/
    } else {
        $("fieldset:not(.fugly) input[type=text]:not(.fugly)").sexy( DFSexyDefaults );
        $("fieldset:not(.fugly) input[type=password]:not(.fugly)").sexy( DFSexyDefaults );
        $("fieldset:not(.fugly) select:not(.fugly)").sexy( DFSexyDefaults );
        $("fieldset:not(.fugly) div.input-sexyList" ).sexyList();
        $("div.sexyToolMenu").sexyToolMenu();
        /*$.each($("fieldset:not(.fugly) legend"), function() {
            $(this).replaceWith($(document.createElement("DIV")).attr("class", "legend").html($(this).html()));
        });*/
    }
}

function sexy( context ) {
    if( context ) {
        $("input[type=text]:not(.fugly)", context ).sexy( DFSexyDefaults );
        $("input[type=password]:not(.fugly)", context ).sexy( DFSexyDefaults );
        $("select:not(.fugly)", context ).sexy( DFSexyDefaults );
        
        //remove these after changing chemical bit
        $("div.input-sexyList", context ).sexyList();
        $("div.sexyToolMenu", context ).sexyToolMenu();
        return context;
    } else {
        $("input[type=text]:not(.fugly)").sexy( DFSexyDefaults );
        $("input[type=password]:not(.fugly)").sexy( DFSexyDefaults );
        $("select:not(.fugly)").sexy( DFSexyDefaults );
        $("div.input-sexyList" ).sexyList();
        $("div.sexyToolMenu" ).sexyToolMenu();
    }
}

function validateHelper(element) {
    var elemId = element.attr("id");
    var x = element.parents("form").eq(0).validate({
    showErrors: function(errors) {
            
            var tooltip = errors[elemId];
            if (tooltip) {

                var sexy = element.data("sexy");
                if (sexy) {
                    sexy.setButtonTooltip(tooltip);
                }
            }
        }
    });
    if (x) {
        x = x.element(element);
    } else {
        return -1;
    }
    var rules = element.rules();
    if (element.val() == "") {
        if (rules && rules.required) {
            return 2;
        } else {
            return -1;
        }
    }

    return x;
}

//SexyList element
jQuery.fn.sexyList = function( options ) {
    this.each( function() {
        var _this = $(this);
        var _width = -1;
        var _height = -1;
        var inputSource = _this.attr( "inputSource" ) ? $( _this.attr( "inputSource" ) ) : null;
        var allowDuplicates = false;
        if( options ) {
            if( options.width != undefined ) {
                _width = options.width;
            }
            if( options.height != undefined ) {
                _height = options.height;
            }
            if( options.inputSource ) {
                inputSource = options.inputSource;
            }
            if(  options.allowDuplicates != undefined && options.allowDuplicates != false &&  
                options.allowDuplicates != "false" ) {
                allowDuplicates = true;
            }
        }
        if( _width == -1 ) {
            var attrWidth = _this.attr( "width" );
            if( attrWidth != undefined && attrWidth != null ) {
                _width = parseInt( attrWidth );
            } else {
                //our default width
                _width = 260;
            }
        }
        if( _height == -1 ) {
            var attrHeight = _this.attr( "height" );
            if( attrHeight != undefined && attrHeight != null ) {
                _height = attrHeight;
            } else {
                _height = 250;
            }
        }
        if( inputSource == null ) {
            //try to find the first input in the previous formfield
            inputSource = $( "select:first", _this.parent().prev() );
        }
        
        
        var _cWidth = _width - 41;
        var _cHeight = _height - 14;
        var _cHeightMargins = _height - 75;
        
        var sexyElement = createDiv()
            .css( "width", _width + "px" )
            .css( "height", _height + "px" )
            .addClass( "ui-sexyList" );
        var sexyElementCanvas = createDiv()
            .css( "width", _cWidth + "px" )
            .css( "height", _cHeight + "px" )
            .addClass( "ui-sexyList-canvas" );
            
        transferAttributes( _this, sexyElement, "id, name" );
            
        sexyElement.append( 
            createDiv().css( "float", "left" ).css( "width", "12px" ).css( "height", _height )
            .append(
                createDiv().addClass( "ui-sexyList-nw" ) )
            .append(
                createDiv().addClass( "ui-sexyList-cw" ).css( "height", _cHeightMargins + "px" ) )
            .append(
                createDiv().addClass( "ui-sexyList-sw" ) ) ).append(
            
            createDiv().css( "float", "right" ).css( "width", "29px" ).css( "height", _height )
            .append(
                createDiv().addClass( "ui-sexyList-ne" ).append(
                    createDiv().addClass( "ui-sexyList-eGap" ) ).append(
                    createDiv().addClass( "ui-sexyList-add" ).attr( "title", "Add item to list" ).click( function() {
                        if( inputSource && inputSource.length > 0 ) {
                            var sexyVal = inputSource.sexyVal();
                            var valueId = sexyVal.value;
                            var value = sexyVal.text;
                            if( !valueId ) { valueId = value; }
                            if( !allowDuplicates ) {
                                //check for duplicacy
                                var isDuplicate = false;
                                $(".ui-sexyList-item", sexyElementCanvas ).each( function() {
                                    if( $(this).attr( "valueId" ) == valueId ) {
                                        isDuplicate = true;
                                        return;
                                    }
                                });
                                if( !isDuplicate ) {
                                    sexyElementCanvas.append( createDiv().addClass( "ui-sexyList-item" )
                                    .attr( "valueId", valueId ).html( value ).click( function() {
                                        $(this).toggleClass( "selected" );
                                    }) );
                                }
                            } else {
                                sexyElementCanvas.append( createDiv().addClass( "ui-sexyList-item" )
                                    .attr( "valueId", valueId ).html( value ).click( function() {
                                        $(this).toggleClass( "selected" );
                                    }) );
                            }
                        }
                    }) ).append( 
                    createDiv().addClass( "ui-sexyList-remove" ).attr( "title", "Remove selected items" ).click( function() {
                        $(".ui-sexyList-item.selected", sexyElementCanvas ).remove();
                    }) ) )
            .append(
                createDiv().addClass( "ui-sexyList-ce" ).css( "height", _cHeightMargins + "px" ) )
            .append( 
                createDiv().addClass( "ui-sexyList-se" ) ) ).append(
            
            createDiv().css( "margin-left", "12px" ).css( "margin-right", "29px" )
                .css( "width", _cWidth + "px" ).css( "height", _height )
            .append(
                createDiv().addClass( "ui-sexyList-nc" ).css( "width", _cWidth + "px" ) )
            .append( sexyElementCanvas )
            .append(
                createDiv().addClass( "ui-sexyList-sc" ).css( "width", _cWidth + "px" ) ) );
       
       _this.replaceWith( sexyElement );
    });
    
    return this;
}

//sexy Tool Menu element
jQuery.fn.sexyToolMenu = function( options ) {
    this.each( function() {
        var _this = $(this);
        
        var title = _this.attr( "title" );
        if( options ) {
            if( !title ) {
                title = options.title ? options.title : "";
            }
        }
        
        var sexyElement = createDiv().addClass( "ui-sexyToolMenu" ).css( "height", "auto" );
        var head = createDiv().addClass( "ui-sexyToolMenu-head" );
        _this.removeAttr( "title" ).removeAttr( "className" ).addClass( "ui-sexyToolMenu-content" );
        var minimizeBt = createDiv().addClass( "ui-sexyToolMenu-minimize" );
        var originalContentHeight = null;
        var originalContent = _this.html();
        var wrapper = createDiv().addClass( "ui-sexyToolMenu-content-wrapper" ).css( "width", "auto" ).css( "height", "auto" );
        wrapper.html( originalContent );
        if( _this.attr( "id" ) ) {
            wrapper.attr( "id", _this.attr( "id" ) );
            _this.removeAttr( "id" );
        }
        _this.empty().append( wrapper );
        
        var collapsedAttr = _this.attr( "collapsed" );
        if( collapsedAttr && collapsedAttr != "false" ) { 
            _this.removeAttr( "collapsed" );
            sexyElement.attr( "collapsed", "true" ); 
            originalContent = _this.html();
            originalContentHeight = _this.height();
            wrapper.css( "display", "none" );
            _this.css( "height", "2px" );
            minimizeBt.toggleClass( "ui-sexyToolMenu-minimize", false );
            minimizeBt.toggleClass( "ui-sexyToolMenu-maximize", true );
            minimizeBt.attr( "title", "Reveal Panel" );
        }
        
        var toggleToolPanel = function(ev) {
            if( minimizeBt.hasClass( "ui-sexyToolMenu-minimize" ) ) {
                originalContentHeight = _this.height();
                originalContent = wrapper.html();
                _this.css( "height", originalContentHeight + "px" );
                //_this.empty();
                wrapper.css( "display", "none" );
                _this.animate({ height: "2px" }, 300 );
                minimizeBt.toggleClass( "ui-sexyToolMenu-minimize", false );
                minimizeBt.toggleClass( "ui-sexyToolMenu-maximize", true );
                minimizeBt.attr( "title", "Reveal Panel" );
                sexyElement.attr( "collapsed", "true" );
            } else {
                _this.animate({ height: originalContentHeight + "px" }, 300, "swing", function() {
                    //_this.append( originalContent );
                    wrapper.css( "display", "block" );
                } );
                minimizeBt.toggleClass( "ui-sexyToolMenu-maximize", false );
                minimizeBt.toggleClass( "ui-sexyToolMenu-minimize", true );
                minimizeBt.attr( "title", "Minimize Panel" );
                sexyElement.attr( "collapsed", "false" );
            }
            
            ev.stopPropagation();
        }
        
        //head.click( toggleToolPanel );
        sexyElement.append( createDiv().addClass( "ui-sexyToolMenu-headContainer" ).append( head
            .append(
                createDiv().addClass( "ui-sexyToolMenu-close" ).click( function() {
                    alert( "Not possible yet!" );
                }) ).append(
                minimizeBt.click( toggleToolPanel ) ).append(
                $(document.createElement( "h3" )).html( title )
                ) ) )
                
        sexyElement.append( _this.replaceWith( sexyElement ) );
    }); 
    
    return this;
}
