$(document).ready(function() {
    $("#login_form").submit(function(event) {
            event.preventDefault();
            var formID = $(this).closest('form').attr('id');
            var data = $('#' + formID).serializeArray();
            
            $.ajaxSetup({cache: false});
            $.ajax({
                type    : "POST",
                cache   : false,
                url     : '/login.php',
                data    : data,
                dateType: 'xml',
                success : function(response) {
                    response = $.parseXML( response );
                    $(response).find("error").each(function() {outputAlert('error',$(this).find("description").text());});
                    $(response).find("success").each(function() {$(window.location).attr('href', $(this).find("redirect").text());});
                },
                error   : function (){
                    alert('System Error');
                }
            });
    });
    
    // Expand Panel
    $("#open").click(function(){$("div#panel").slideDown("slow");});	

    // Collapse Panel
    $("#close").click(function(){$("div#panel").slideUp("slow");});

    // Switch buttons from "Log In | Register" to "Close Panel" on click
    $("#toggle a").click(function () {$("#toggle a").toggle();});
});

var newAlert = function(xml) {
    $(xml).find("success").each(function() {outputAlert('success',$(this).find("description").text());});
    $(xml).find("error").each(function() {outputAlert('error',$(this).find("description").text());});
    $(xml).find("warning").each(function() {outputAlert('warning',$(this).find("description").text());});
    $(xml).find("notice").each(function() {outputAlert('notice',$(this).find("description").text());});
    $(xml).find("unknown").each(function() {outputAlert('unknown',$(this).find("description").text());});
};

var outputAlert = function(type,description) {
    var randomnumber = Math.floor(Math.random()*110);

    $('#notifications').append(
        '<div class="alert-' + type + '" id="' + randomnumber +'" style="display:none;">' + description + '<!-- <span class="close_notification">Close</span> --></div>');
    $('#' + randomnumber).slideDown();
};

var saveFormData = function() {    
    var formID = $(this).closest('form').attr('id');
    $('#' + formID + '_loading').show();
    
    var buttonID = $(this).attr('id');
    $('#' + buttonID).attr("disabled", true);
    
    var data = $('#' + formID).serializeArray();
    data.push({name: 'button_id', value: buttonID});

    $.ajax({
        type    : "POST",
        cache   : false,
        url     : '/process_ajax.php',
        data    : data,
        success : function(data) {
            data = $.parseXML( data );
            newAlert(data);
            $('#' + formID + '_loading').hide();
            $('#' + buttonID).attr("disabled", false );
            $(data).find("redirect").each(function() {$(window.location).attr('href', $(this).text());});
        },
        error   : function (xhr, ajaxOptions, thrownError){
            alert(xhr.responseText);
        }
    });
    return false;
};

// Use the Following line of code to process a form
// $('#form_id_save_button').live('click' ,saveFormData );

// Additional functions
//String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }
//String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
//String.prototype.rtrim = function() { return this.replace(/\s+$/,""); }

(function($){
    // Toggled Panes
    $('.toggled-pane .toggled-pane-heading').live('click', function() {
        if ( $(this).hasClass('open') )
            $(this).removeClass('open');
        else
            $(this).addClass('open');

        //$(this).parent('.toggled-pane').find('.toggled-pane-content').animate({ opacity: 'toggle', height: 'toggle' }, 300);
        $(this).parent('.toggled-pane').find('.toggled-pane-content').slideToggle();
    });
})(jQuery);

/*!
// iPhone-style Checkboxes jQuery plugin
// Copyright Thomas Reynolds, licensed GPL & MIT
*/
;(function($, iphoneStyle) {

// Constructor
$[iphoneStyle] = function(elem, options) {
  this.$elem = $(elem);
  
  // Import options into instance variables
  var obj = this;
  $.each(options, function(key, value) {
    obj[key] = value;
  });
  
  // Initialize the control
  this.wrapCheckboxWithDivs();
  this.attachEvents();
  this.disableTextSelection();
  
  if (this.resizeHandle)    {this.optionallyResize('handle');}
  if (this.resizeContainer) {this.optionallyResize('container');}
  
  this.initialPosition();
};

$.extend($[iphoneStyle].prototype, {
  // Wrap the existing input[type=checkbox] with divs for styling and grab DOM references to the created nodes
  wrapCheckboxWithDivs: function() {
    this.$elem.wrap('<div class="' + this.containerClass + '" />');
    this.container = this.$elem.parent();
    
    this.offLabel  = $('<label class="'+ this.labelOffClass +'">' +
                         '<span>'+ this.uncheckedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.offSpan   = this.offLabel.children('span');
    
    this.onLabel   = $('<label class="'+ this.labelOnClass +'">' +
                         '<span>'+ this.checkedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.onSpan    = this.onLabel.children('span');
    
    this.handle    = $('<div class="' + this.handleClass + '">' +
                         '<div class="' + this.handleRightClass + '">' +
                           '<div class="' + this.handleCenterClass + '" />' +
                         '</div>' +
                       '</div>').appendTo(this.container);
  },
  
  // Disable IE text selection, other browsers are handled in CSS
  disableTextSelection: function() {
    if (!$.browser.msie) {return;}

    // Elements containing text should be unselectable
    $.each([this.handle, this.offLabel, this.onLabel, this.container], function() {
      $(this).attr("unselectable", "on");
    });
  },
  
  // Automatically resize the handle or container
  optionallyResize: function(mode) {
    var onLabelWidth  = this.onLabel.width(),
        offLabelWidth = this.offLabel.width();
        
    if (mode == 'container') {
      var newWidth = (onLabelWidth > offLabelWidth) ? onLabelWidth : offLabelWidth;
      newWidth += this.handle.width() + 15; 
    } else { 
      var newWidth = (onLabelWidth < offLabelWidth) ? onLabelWidth : offLabelWidth;
    }
    
    this[mode].css({width: newWidth});
  },
  
  attachEvents: function() {
    var obj = this;
    
    // A mousedown anywhere in the control will start tracking for dragging
    this.container
      .bind('mousedown touchstart', function(event) {          
        event.preventDefault();
        
        if (obj.$elem.is(':disabled')) {return;}
          
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $[iphoneStyle].currentlyClicking = obj.handle;
        $[iphoneStyle].dragStartPosition = x;
        $[iphoneStyle].handleLeftOffset  = parseInt(obj.handle.css('left'), 10) || 0;
        $[iphoneStyle].dragStartedOn     = obj.$elem;
      })
    
      // Utilize event bubbling to handle drag on any element beneath the container
      .bind('iPhoneDrag', function(event, x) {
        event.preventDefault();
        
        if (obj.$elem.is(':disabled')) {return;}
        if (obj.$elem != $[iphoneStyle].dragStartedOn) {return;}
        
        var p = (x + $[iphoneStyle].handleLeftOffset - $[iphoneStyle].dragStartPosition) / obj.rightSide;
        if (p < 0) {p = 0;}
        if (p > 1) {p = 1;}
        obj.handle.css({left: p * obj.rightSide});
        obj.onLabel.css({width: p * obj.rightSide + 4});
        obj.offSpan.css({marginRight: -p * obj.rightSide});
        obj.onSpan.css({marginLeft: -(1 - p) * obj.rightSide});
      })
    
        // Utilize event bubbling to handle drag end on any element beneath the container
      .bind('iPhoneDragEnd', function(event, x) {
        if (obj.$elem.is(':disabled')) {return;}
        
        var checked;
        if ($[iphoneStyle].dragging) {
          var p = (x - $[iphoneStyle].dragStartPosition) / obj.rightSide;
          checked = (p < 0) ? Math.abs(p) < 0.5 : p >= 0.5;
        } else {
          checked = !obj.$elem.attr('checked');
        }
        
        obj.$elem.attr('checked', checked);

        $[iphoneStyle].currentlyClicking = null;
        $[iphoneStyle].dragging = null;
        obj.$elem.change();
      });
  
    // Animate when we get a change event
    this.$elem.change(function() {
      if (obj.$elem.is(':disabled')) {
        obj.container.addClass(obj.disabledClass);
        return false;
      } else {
        obj.container.removeClass(obj.disabledClass);
      }
      
      var new_left = obj.$elem.attr('checked') ? obj.rightSide : 0;

      obj.handle.animate({left: new_left},                 obj.duration);
      obj.onLabel.animate({width: new_left + 4},             obj.duration);
      obj.offSpan.animate({marginRight: -new_left},                obj.duration);
      obj.onSpan.animate({marginLeft: new_left - obj.rightSide}, obj.duration);
    });
  },
  
  // Setup the control's inital position
  initialPosition: function() {
    this.offLabel.css({width: this.container.width() - 5});

    var offset = ($.browser.msie && $.browser.version < 7) ? 3 : 6;
    this.rightSide = this.container.width() - this.handle.width() - offset;

    if (this.$elem.is(':checked')) {
      this.handle.css({left: this.rightSide});
      this.onLabel.css({width: this.rightSide + 4});
      this.offSpan.css({marginRight: -this.rightSide});
    } else {
      this.onLabel.css({width: 0});
      this.onSpan.css({marginLeft: -this.rightSide});
    }
    
    if (this.$elem.is(':disabled')) {
      this.container.addClass(this.disabledClass);
    }
  }
});

// jQuery-specific code
$.fn[iphoneStyle] = function(options) {
  var checkboxes = this.filter(':checkbox');
  
  // Fail early if we don't have any checkboxes passed in
  if (!checkboxes.length) {return this;}
  
  // Merge options passed in with global defaults
  var opt = $.extend({}, $[iphoneStyle].defaults, options);
  
  checkboxes.each(function() {
    $(this).data(iphoneStyle, new $[iphoneStyle](this, opt));
  });

  if (!$[iphoneStyle].initComplete) {
    // As the mouse moves on the page, animate if we are in a drag state
    $(document)
      .bind('mousemove touchmove', function(event) {
        if (!$[iphoneStyle].currentlyClicking) {return;}
        event.preventDefault();
        
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        if (!$[iphoneStyle].dragging &&
            (Math.abs($[iphoneStyle].dragStartPosition - x) > opt.dragThreshold)) { 
          $[iphoneStyle].dragging = true; 
        }
    
        $(event.target).trigger('iPhoneDrag', [x]);
      })

      // When the mouse comes up, leave drag state
      .bind('mouseup touchend', function(event) {        
        if (!$[iphoneStyle].currentlyClicking) {return;}
        event.preventDefault();
    
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $($[iphoneStyle].currentlyClicking).trigger('iPhoneDragEnd', [x]);
      });
      
    $[iphoneStyle].initComplete = true;
  }
  
  return this;
}; // End of $.fn[iphoneStyle]

$[iphoneStyle].defaults = {
  duration:          200,                       // Time spent during slide animation
  checkedLabel:      'ON',                      // Text content of "on" state
  uncheckedLabel:    'OFF',                     // Text content of "off" state
  resizeHandle:      true,                      // Automatically resize the handle to cover either label
  resizeContainer:   true,                      // Automatically resize the widget to contain the labels
  disabledClass:     'iPhoneCheckDisabled',
  containerClass:    'iPhoneCheckContainer',
  labelOnClass:      'iPhoneCheckLabelOn',
  labelOffClass:     'iPhoneCheckLabelOff',
  handleClass:       'iPhoneCheckHandle',
  handleCenterClass: 'iPhoneCheckHandleCenter',
  handleRightClass:  'iPhoneCheckHandleRight',
  dragThreshold:     5                          // Pixels that must be dragged for a click to be ignored
};

})(jQuery, 'iphoneStyle');

//
// ToggleEdit Forms
$.widget( "ui.toggleEdit", {
    options: {
        types: [
        /*
		{
			is:function( e ){
				return e[0].tagName==="SELECT";            
			},
			text:function( e ){
				return "test";            
			}
		}
		*/
        ],
        copyCss: false,
        eventsEnabled:true,
        events: {},
        listeners: {},
        delay: 1000
    },
    defaults:{
        events:{
            edit: "click",
            delayedit: false,
            canceledit: false,
            preview: "mouseleave",
            cancelpreview: "mouseenter",
            delaypreview: 800
        },
        listeners:{
            edit: "p",
            canceledit: "p",
            preview: "e",
            cancelpreview: "e"
        }    
    },
    _init: function() {
        var s = this;
        var e = s.element;
        var o = s.options;
        
        //bugfix deep default options are overridden on second init. still need to find source issue
        o.events = $.extend(true, {}, s.defaults.events, o.events);
        o.listeners = $.extend(true, {}, s.defaults.listeners, o.listeners);
        
		//skip submit buttons and hidden fields
        if ( e.is( ":submit" ) || e.is( "input[type=hidden]" ) ) {
            return false;
        }

		//cleanup
        if ( typeof e.data( "toggleEdit-preview" ) !== "undefined" ) {
            s.clear();
            s.disableEvents();
        }

		//init preview element
        s.p = $( "<div class=\"toggleEdit toggleEdit-preview toggleEdit-preview-" + s._tag( e ) + "\"></div>" )
        .insertAfter( e );

        e
        .addClass( "toggleEdit toggleEdit-edit toggleEdit-edit-" + s._tag( e ) )
		//store reference to preview element
        .data( "toggleEdit-preview", s.p );
        
        s.eventsEnabled = o.eventsEnabled;
		
        if ( s.eventsEnabled ) {
            s.enableEvents();
        }

    },
    toggle: function() {
        var s = this;

        if ( s.edit ) {
            s.preview();
        } else {
            s.edit();
        }
    },
    edit: function( event ) {
        var s = this;
        var e = s.element;

        s.editmode = true;
		
        s.text = s._parseValue( e );
        s.p.hide();
        e.show();
        s._trigger( "onedit", event, {
            text: s.text,
            preview: s.p,
            element: e
        });
    },
    preview: function( event ) {
        var s = this;
        var e = s.element;

        s.editmode = false;
        s.text = s._parseValue();
        e.hide();
        s._setup();
        s.p.show();
        s._trigger( "onpreview", event, {
            text: s.text,
            preview: s.p,
            element: e
        });
    },
    previewEl: function() {
        return this.p;
    },
    _tag: function( e ) {
        return e.get( 0 ).tagName.toLowerCase();
    },
    _parseValue: function() {
        var s = this;
        var e = s.element;
        var o = s.options;
		var i;
		
        //custom inputs overide defaults
        for ( i = 0; i < o.types.length; i++ ) {
            if ( $.isFunction( o.types[i].is ) && $.isFunction( o.types[i].text ) ) {
                if ( o.types[i].is( e ) ) {
                    return o.types[i].text( e );
                }
            }
        }

        if ( e.is( "select" ) ) {
            return e.find( "option[value=" + e.val() + "]" ).text();
        } else {
            if ( e.is( ":checkbox" ) ) {
                if ( e.is( ":checked" ) ) {
                    return "Yes";
                } else {
                    return "No";
                }
            }
            return e.val();
        }
    },
    _listner: function( selector ) {
        var s = this;
        var e = s.element;

        switch ( selector ) {
        case "e":
            return e;
        case "p":
            return s.p;
        default:
            return $( selector );
        }
    },
	//applies css to and populates preview element
    _setup: function() {
        var s = this;
        var e = s.element;
        var o = s.options;
        var css = {};

        if ( o.copyCss ) {
            var width = e.width();
            var height = e.height();
            var display = e.css( "display" );
            var floatVal = e.css( "float" );
            if ( !e.is( ":checkbox" ) ) {
                if ( width ) {
                    css.width = width;
                }
                if ( height ) {
                    css.height = height;
                }
            }

            if ( display ) {
                css.display = display;
            }
            if ( floatVal ) {
                css.floatVal = floatVal;
            }
        }

        s.p
        .css( css )
        .html( s.text );
    },
    enableEvents: function( edit ) {
        var s = this;
        var e = s.element;
        var o = s.options;
        s.editmode = true;

		//store event handlers so that they can be unbound during cleanup
        s.handlers = {
            preview: {
                trigger: function( event ) {
                    if ( !o.events.delaypreview ) {
                        s.preview( event );
                    } else {
                        s.handlers.preview.timeout = setTimeout( function() {
                            s.preview( event );
                        },
                        o.events.delaypreview );
                    }
                },
                cancel: function() {
                    clearTimeout( s.handlers.preview.timeout );
                    s._trigger( "cancelpreview", event, {
                        text: s.text,
                        preview: s.p,
                        element: e
                    });
                }
            },
            edit: {
                trigger: function( event ) {
                    if ( !o.events.delayedit ) {
                        s.edit( event );
                    } else {
                        s.handlers.edit.timeout = setTimeout( function() {
                            s.edit( event );
                        },
                        o.events.delayedit );
                    }
                },
                cancel: function() {
                    clearTimeout( s.handlers.edit.timeout );
                    s._trigger( "canceledit", event, {
                        text: s.text,
                        preview: s.p,
                        element: e
                    });
                }
            }
        };

        s._listner( o.listeners.edit ).bind( o.events.edit, s.handlers.edit.trigger );
        if ( o.events.canceledit && o.events.delayedit ) {
            s.handlers.edit.cancel = function() {
	            //cancel switch to edit mode
                clearTimeout( s.handlers.edit.timeout );
            };
            s._listner( o.listeners.canceledit ).bind( o.events.canceledit, s.handlers.edit.cancel );
        }

        s._listner( o.listeners.preview ).bind( o.events.preview, s.handlers.preview.trigger );
        if ( o.events.cancelpreview && o.events.delaypreview ) {
            s.handlers.preview.cancel = function() {
				//cancel switch to preview mode
                clearTimeout( s.handlers.preview.timeout );
            };
            s._listner( o.listeners.cancelpreview ).bind( o.events.cancelpreview, s.handlers.preview.cancel );
        }

		//mode to default to on enabling the events
        if ( edit ) {
            s.edit();
        } else {
            s.preview();
        }
        s.eventsEnabled = true;
    },
    disableEvents: function() {
        var s = this;
        var e = s.element;
        var o = s.options;

        e.unbind( o.events.preview, s.handlers.preview.trigger );
        if ( s.handlers.preview.cancel ) {
            e.unbind( o.events.cancelpreview, s.handlers.preview.cancel );
        }
        e.unbind( o.events.edit, s.handlers.edit.trigger );
        if ( s.handlers.edit.cancel ) {
            e.unbind( o.events.canceledit, s.handlers.edit.cancel );
        }
        s.eventsEnabled = false;
    },
    clear: function() {
        var s = this;
        var e = s.element;

        e.data( "toggleEdit-preview" ).remove();
        e.data( "toggleEdit-preview", null );
        e.show();
    },
    destroy: function() {
        this.clear();
        this.disableEvents();
        $.Widget.prototype.destroy.apply( this, arguments );
    }
});
