 // tabs - jQuery plugin for accessible, unobtrusive tabs by Klaus Hartl
// v 1.2
// http://stilbuero.de/tabs/
// Free beer and free speech. Enjoy!

$.fn.tabs = function(options) {
    // basic stuff
    var ON_CLASS = 'on';
    var OFF_CLASS = 'tabs-hide';
    // options
    var on = options && options.on && (typeof options.on == 'number' && options.on > 0) ? options.on - 1 : 0;
    return this.each(function() {
        var re = /([_\-\w]+$)/i;
        // retrieve active tab from hash in url
        if (location.hash) {
            var hashId = location.hash.replace('#', '');
            $(this).find('>ul>li>a').each(function(i) {
                if (re.exec(this.href)[1] == hashId) {
                    on = i;
                    var unFocus = function() { // required to not scroll to fragment
                        scrollTo(0, 0);
                    }
                    // be nice to IE via Conditional Compilation
                    // this needs to preceed call to unFocus for other browsers
                    /*@cc_on
                    //location.replace('#'); // required to not scroll to fragment
                    setTimeout(unFocus, 150); // IE needs a little timeout here
                    @*/
                    unFocus();
                    setTimeout(unFocus, 100); // be nice to Opera
                }
            });
        }
		
        $(this).find('>div').not(':eq(' + on + ')').addClass(OFF_CLASS);
        $(this).find('>ul>li:eq(' + on + ')').addClass(ON_CLASS);
        var container = this;
        var undefined;
        $(this).find('>ul>li>a').click(function() {
            if (!$(this.parentNode).is('.' + ON_CLASS)) {
				// decode our target id by using regex
				var targetid = re.exec(this.href)[1]
				// get object to target
                var target = $('#' + targetid);
				// does target exist?
                if (target.size() > 0) {

                    var self = this;
                    var visible = $(container).find('>div:visible');
                    if (options && options.slide && options.fade) {
                        visible.slideUp(options.slide).fadeOut(options.fade, function() {
                            // TODO check accessibility for fade
                            $(this).addClass(OFF_CLASS).css({display: '', height: 'auto'}); // retain acccessibility for print and other media types
                            $(container).find('>ul>li').removeClass(ON_CLASS);
                            $(self.parentNode).addClass(ON_CLASS);
                            target.css('display', 'none').removeClass(OFF_CLASS).slideDown(options.slide);
                        });
                    } else if (options && options.slide) {
                        visible.slideUp(options.slide, function() {
                            $(this).addClass(OFF_CLASS).css({display: '', height: 'auto'}); // retain acccessibility for print and other media types
                            $(container).find('>ul>li').removeClass(ON_CLASS);
                            $(self.parentNode).addClass(ON_CLASS);
                            target.css('display', 'none').removeClass(OFF_CLASS).slideDown(options.slide);
                        });
                    } else if (options && options.fade) {
                        visible.fadeOut(options.fade, function() {
                            // TODO check accessibility for fade
                            $(this).addClass(OFF_CLASS).css({display: '', opacity: '1'}); // retain acccessibility for print and other media types
                            $(container).find('>ul>li').removeClass(ON_CLASS);
                            $(self.parentNode).addClass(ON_CLASS);
                            target.css('display', 'none').removeClass(OFF_CLASS).fadeIn(options.fade);
                        });
                    } else {
                        visible.addClass(OFF_CLASS);
                        $(container).find('>ul>li').removeClass(ON_CLASS);
                        $(this.parentNode).addClass(ON_CLASS);
                        target.removeClass(OFF_CLASS);
                    }
					
					
					
					// before we continue with showing the target, lets
					// determine whether ajax load is necessary. This is
					// only the case when title attribute has been set in
					// the target div
					var loadfrom = document.getElementById( targetid).title;
					if (loadfrom.length > 0) {
						if (options && options.loadingcontent) {
							var ldc = document.getElementById(options.loadingcontent)
							if ( ldc){
								target.html(ldc.innerHTML);
							}
						}
						// check whether we need to completely update the div with
						// received data or we need to parse an element/path
						if ((options && options.showelement) ||(options && options.showpath)) {
							 $.ajaxSetup( {
							   async: false
							 } );

							$.get( loadfrom, 
								function(response) {
									alert('loadde');
									// borrowed from prototype - not really needed but what the heck
									var TryToExec = {
									  these: function() {
										var returnValue;
										for (var i = 0; i < arguments.length; i++) {
										  var lambda = arguments[i];
										  try {
											returnValue = lambda();
											break;
										  } catch (e) {}
										}
										return returnValue;
									  }
									};
									// when using showelement, we will parse it ourselves
									// by using REXML
									if (options && options.showelement) {
										var outputresult = ""
										var xmlDoc = new REXML( response);
										for (var xmlIterator=new JSXMLIterator(xmlDoc.rootElement); xmlIterator.getNextNode();) {
											if (xmlIterator.xmleElem.attribute('id') == options.showelement) {
												//target.html( xmlIterator.xmleElem.getAll());	
												outputresult = xmlIterator.xmleElem.getAll();
												break;
											}
										}
										if (outputresult == ""){
											outputresult = "Unable to find the text with given id: "+options.showelement;
										}
										//target.html( outputresult);
										//document.getElementById( targetid).innerHTML = outputresult;
										target.html('');
										target.append( outputresult);
									}
									else{
										// for (x)path, we will have to use the built-in dom
										// parsers, so parse the response as to xml
										var xmlResponse = TryToExec.these(
											function() { 
												return new DOMParser().parseFromString(response, 'text/xml'); 
											},
											function() { 
												var xmldom = new ActiveXObject('Microsoft.XMLDOM'); 
												xmldom.loadXML(response); 
												if (xmldom.parseError.errorCode == 0) {
													return xmldom; 
												}
												else{
													// parsing did not succeed...
													// see xmldom.parseError.reason / linepos / srcText
													// IE is quite strict on DTD, so make sure you validate
													// the loaded file
													return null;
												}
											}
										)|| null;
		
										if (xmlResponse != null) {
											target.html( $(options.showpath, xmlResponse).text());
										}
										else {
											target.html( "Unable to parse loaded XML file!");
										}
									}
								}
							);
						}
						else {
							target.load( loadfrom);
						}
						// we will empty the title, so it will not get loaded again
						// unless this is overruled by a setting..
						if (!(options && options.alwaysreload)){
							if (options.alwaysreload == 0) {
								document.getElementById( targetid).title = '';
							}
						}
						// now check whether we need to update the tab text
						// after the load.
						if (options && options.tabtextafterload){
							if (options.tabtextafterload[targetid] != null) {
								$(this).html(options.tabtextafterload[targetid]);
							}
						}
						
						if (options && options.afterload) {
							var doaload = function(){
								options.afterload( targetid);
							};
							// we give some time for the browser
							// to get everthing worked out...without
							// this timeout, firefox looses it.
							setTimeout(doaload, 300);
						}
						
					}					
					
					
					
					
					
                } else {
                    alert('There is no such container.');
                }
            }
            return false;
        });
    });
};
