/**
 * --------------------------------
 * - Global Functions autobild.de -
 * --------------------------------
*/
// Do not load more than once
if(typeof window.AUBIGL == "undefined") {

	// The big bad voodoo daddy:
	var AUBIGL = {
		version: "2.1", // Version of this JS
		ie_version: parseInt((navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/)||[9,9])[1],10), // IE mayor version
		cstore: {}, // Storage
		menuto: 500, // Make main menues invisible after n msec
		max_tabs: 3, // Maximum number of tabs per modules (keep this LOW)
		done_init: false, // If init done
		jq_init: null, // JQUERY Flag
		regged_cleanup: false,	
    sas_tmstp : Math.round(Math.random()*10000000000), // fuer neuer smart AdServer
    sas_masterflag : 1, // fuer neuer smart AdServer

    /*
     * Aufruf fuer neuer Smart AdServer
     */
    smart_ad_server: function(sas_pageid, sas_formatid, sas_target) {
      if (this.sas_masterflag == 1) {
        this.sas_masterflag = 0;
        sas_master = 'M';
      } else {
        sas_master = 'S';
      }
      document.write('<SCR'+'IPT SRC="http://www.smartadserver.com/call/pubj/' +
      sas_pageid + '/' + sas_formatid + '/'+sas_master + '/' + this.sas_tmstp + '/' +
      escape(sas_target) + '?"></SCR'+'IPT>');
    },

    /*
		 * Initialize operation
		 */
		init_ready: function() {
			// Register UNLOAD to clean up the DOM
			if(!this.regged_cleanup) {
				$(window).unload(function() { AUBIGL.cleanup(); });
				this.regged_cleanup = true;
			}

			if(isu(this.cstore.sel_smenu)) {
				this.cstore.sel_smenu = true;
				this.cstore.mmenu = "x";
				this.cstore.sel_mmenu = false;
				this.cstore.to = false;
			}

			// Websitesearch
			this.impl_search();

			// Implement :hover for non link-elements in IE < 7
			if(this.ie_version < 7) {
				this.impl_hover_ie(false);

				// Fix PNG in IE<7
				this.pngfix();
			}

			// Implement "cmd" commands in id of elements
			this.impl_cmds();

			// Initialize <form>s
			this.init_forms();

			// Implement open/close toggle for "treeview"
			this.impl_treeview();

            // Quickfix ANZEIGE
            $("li.nav_anzeige").mouseover(function() {
                $(".info_anzeige",this).show();
            })
            .mouseout(function() {
                $(".info_anzeige",this).hide();
            });

            if(this.ie_version < 7) {
                $("li.nav_anzeige a").mouseover(function() {
                    var parent = $(this).parents("li");
                    $(".info_anzeige",parent).show();
                })
                .mouseout(function() {
                    var parent = $(this).parents("li");
                    $(".info_anzeige",parent).hide();
                });
            }

            /* Clicktracker */
			$("body").click(function(e) {
				var el = $(e.target);
				if(el.is("a")) {
				} else if(el.is("input") && el.attr("type") == "submit") {
					el = el.parents("form");
				} else if(!el.is("a")) {
					el = el.parents("a");
					if(el.length < 1) {
						return true;
					}
				}
				return AUBIGL._ct.track(el[0]);
			});
		},

		/**
		 * PNG Fix fuer IE < 7
		 */
		pngfix: function() {
			// Nur wenn wir auf www.autobild.de sind
			// www.autobild.de
			if(document.URL.indexOf(".autobild.de") > 0)
			{
				// Alle Bilder holen, die anders als mit weissem BG dargestellt werden
				$("div.teaser-highlight1 img").each(function(i,e)
				{
					// Im Pfad ir_img und ein PNG?
				    if(e.src.indexOf("ir_img") > 0 &&e.src.substring(e.src.length-3, e.src.length).toUpperCase() == "PNG") {
				    	$(e).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+e.src+"', sizingMethod='scale')");
				    	e.src="http://www.autobild.de/img/transparent.gif";
				    }
				});
			}
		},

		/**
		 * Implement Websitesearch filling and cleaning of container
		 */
		impl_search: function () {
		  var textfield = $("input.websitesearch");
		  var send = $("input.websitesearch_send");
		  
		  //init
		  $(textfield).each(function() {        
        if($(this).attr('value') == '') {
          $(this).addClass('light');
          $(this).attr('value', this.title);
        }
      });
      
      //events
			textfield
			.unbind("focus")
			.bind("focus",function() {
				if (this.value == this.title) {
				  $(this).removeClass('light');
					$(this).attr('value', '');
				}
			})
			.bind("blur",function () {
				if ($.trim(this.value) == '') {
				  $(this).addClass('light');
					$(this).attr('value', this.title);
				}
			});
			
			send.click(function() {
			  var input = $(this).prev();
	      if(input.val() == input.attr('title')) {
			    input.val('');
			  }
			});
		},

		/*
		 * Implement :hover pseudoclass for IE < 7
		 * IE 6 does only accept :hover for <a> elements. That sucks.
		 * Is only called if IE Version < 7 is detected (see init_ready function)
		 */
		impl_hover_ie: function(check) {
			var that=this;

			// Check for "out of menu"
			if(check) {
				// If no submenu or mainmenu is selected: remove it.
				if(!that.cstore.sel_smenu || !that.cstore.sel_mmenu) {
					// Remove hover class and ...
					$("#"+that.cstore.mmenu).removeClass("hover");

					// ... show selects again
					$("#content select").show();

					// Reset cstore
					this.cstore.mmenu = "x";
					this.cstore.sel_mmenu = true;
					this.cstore.sel_smenu = true;
				}
				that.cstore.to = false;
				return;
			}

			// Attach to MAIN-Menu
			$("#nav>li").mouseover(function() {
				// Only fire if this is NOT the same element as before
				// Seems that an <a> fires the li-event?!
				AUBIGL.cstore.sel_mmenu = true;
				// Important: simulate open submenu:
				AUBIGL.cstore.sel_smenu = true;
				if(this.id != that.cstore.mmenu) {
					// remove visibility of old menu
					$("#"+that.cstore.mmenu).removeClass("hover");
					// make this menu visible
					$(this).addClass("hover");
					// remember me
					that.cstore.mmenu = this.id;

					// Hide <select>: IE displays them OVERLAYING the menu
					$("#content select").hide();
				}
				return false;
			});

			// mouseout triggers even when mouse moves from <li> to inner <a>!
			$("#nav>li").mouseout(function() {
				AUBIGL.cstore.sel_mmenu = false;
				if(!that.cstore.to) {
					window.setTimeout("AUBIGL.impl_hover_ie(true)",that.menuto);
					that.cstore.to = true;
				}
				return false;
			});

			// Attach to submenu
			$("#nav>li li").mouseover(function() {
				// submenu selected:
				that.cstore.sel_smenu = true;
				AUBIGL.cstore.sel_mmenu = true;

				// remove hover class from <li>s of current menu. (not neccessary?)
				//$("#"+that.cstore.mmenu+" li").removeClass("hover");

				// make this submenu visible
				$(this).addClass("hover");

				return false;
			});

			$("#nav>li li").mouseout(function() {
				that.cstore.sel_smenu = false;
				if(!that.cstore.to) {
					window.setTimeout("AUBIGL.impl_hover_ie(true)",that.menuto);
					that.cstore.to = true;
				}
				return false;
			});

			// Bind "mouseout" to links inside mainmenu <li> to cancel event bubble
			// Simpulate a selected submenu to leave the mainmenu open
			$("#nav div a")
			.mouseout(function() {
				AUBIGL.cstore.sel_mmenu = true;
				return false;
			})
			.mouseover(function()
			{
				AUBIGL.cstore.sel_mmenu = true;
				return false;
			});
		},

		/*
		 * Implements "cmd" commands for elements whose id starts with "cmd"
		 * Commands structure:
		 * cmd-COMMAND_COMMANDVALUE
		 *
		 * COMMANDS:
		 *
		 * toggleblock: Toggle visibility of block in formassistant
		 * togglemod: Toggle visibility of module
		 * hoverstar: Show stars for voting
		 * sethersteller: Sets Make of selected Model in textfield
		 *
		 */
		impl_cmds: function() {
			var tmp, idx, el = null;
			var cmd = "";
			var val = "";

			// Search in the following elements:
			// TODO: ul[@id^='cmd-'] wird nicht benoetigt?
			$("a[id^='cmd-'], div[id^='cmd-'], select[id^='cmd-']").each(function(idx, el) {
				// If not an empty element
				if(!isu(el.id)) {
					// Split command name
					tmp = el.id.indexOf("_");
					cmd = el.id.substring(0,tmp);
					val = el.id.substring(tmp+1);

					// Which command?
					switch(cmd) {
						/*
						 * toggleblock:
						 * ------------
						 *
						 * Toggles visibility of grouped input elements (aka. form-assistant)
						 * Demo in "demo_global_block_mod_hoverstars.html"
						 */
						case "cmd-toggleblock":
							// CLICK: Make assistant visible or invisible
							$(el).click(function() {
								// Toggle visibility of block in assistant
								$("#"+el.id.substring(el.id.indexOf("_")+1))
								.toggleClass("item-expanded")
								// Do not make click "visible"
								.blur();
							});
							break;
						/*
						 * togglemod:
						 * ----------
						 *
						 * Toggles visibility of modules
						 * Demo in "demo_global_block_mod_hoverstars.html"
						 */
						case "cmd-togglemod":
							// CLICK: Make module visible or invisible
							$(el).click(function() {
							    // Toggle visibility on parent of selector
							   var par = $(el).parent();
							    par.toggleClass("mod-collapsed").blur();
								// Set cookie (parent element, key of module)
								AUBIGL.modul_set_cookie(par);
							  });
							break;
						/*
						 * hoverstar:
						 * ----------
						 *
						 * Shows the right number of "stars" and he corresponding textmessage for "Artikel bewerten"
						 * Demo in "demo_global_block_mod_hoverstars.html"
						 */
						case "cmd-hoverstar":
							starState = Array();

							// MOUSEOVER: show stars up to this point
							$(el).mouseover(function() {
								// Parent Node
								var dad = $(this).parent().parent();
								// Show correct title attribute text:
								var text = $("#rating-cleartext_"+dad.attr("id"));
								$("span:nth-child(1)",text).hide();
								$("span:nth-child(2)",text).empty().prepend("&nbsp;"+$(this).attr("title")).css("display","inline");
								// Display correct number of "stars"
								var curr_star = this.id.substring(this.id.lastIndexOf("_")+1);
								$(".star",dad).each(function(i) {
									starState[i] = this.className;
									if(i < curr_star) {
										$(this).removeClass("star-off").addClass("star-on");
									} else {
										$(this).removeClass("star-on").addClass("star-off");
									}
								});
							});
							// MOUSEOUT: remove stars and text
							$(el).mouseout(function() {
								// Parent Node
								var dad = $(this).parent().parent();
								// Show default text:
								var text = $("#rating-cleartext_"+dad.attr("id"));
								$("span:nth-child(2)",text).hide();
								$("span:nth-child(1)",text).css("display","inline");
								// Display no "stars"!
								$(".star",dad).each(function(i) {
									this.className = starState[i];
								});
							});
							// CLICK: Blur it and don't submit
							$(el).click(function() {
								var dad = $(this).parent().parent();
								var curr_star = $(this).attr("id").substring(this.id.lastIndexOf("_")+1);
								var star_group = dad[0].id.replace(/^.*_bar/,'');
								var f = 0;
								$(".star",dad).each(function(i) {
									starState[i] = this.className;
									if(i < curr_star) {
										$(this).removeClass("star-off").addClass("star-on");
									} else {
										$(this).removeClass("star-on").addClass("star-off");
									}
								});
								$("input",dad).val(curr_star);
								var text = $("#rating-cleartext_"+dad.attr("id"));
								$("span:nth-child(1)",text).empty().prepend("&nbsp;"+$(this).attr("title")).css("display","inline");
								$("span:nth-child(2)",text).hide();
								this.blur();
								return false;
							});
							break;
						case "cmd-withdrawvote":
							// reset vote to default
							$(el).click(function() {
								// parent node
								var dad = $(this).parent().parent();
								var bar = $("div[id^='voting_bar']",dad);
								$(".star",bar).each(function(i) {
                                    $(this).removeClass("star-on").addClass("star-off");
								});
								var text = $("#rating-cleartext_"+bar.attr("id"));
								$("span:nth-child(1)",text).empty().prepend("&nbsp;").css("display","inline");
								$("span:nth-child(2)",text).hide();
								$("input",bar).val(0);
								this.blur();
								return false;
							});
							break;
						/*
						 * sethersteller:
						 * --------------
						 *
						 * Displays the corresponding make for a selected model in car-comparison
						 * Demo in "demo_global_sethersteller.html"
						 */
						case "cmd-sethersteller":
							// CHANGE: Change make of select field to correct corresponding label
							$(el).change(function() {
								// change TARGET (<th>) innerHTML to value of the label from the parent <optgroup>
								$("#"+this.id.substring(this.id.lastIndexOf("_")+1)).empty().prepend($("option:selected",this).parent().attr("label"));
							});
							break;
					}
				}
			});
		},

		/*
		 * Initialize <form> fields
		 * Highlight non-empty fields
		 * Demo in "demo_global_sethersteller.html"
		 */
		init_forms: function() {
			var idx, el = null;
			$("input.highlight-input, select.highlight-input, textarea.highlight-input").each(function(idx, el) {
				var el = $(el);
				if(el.is("select")) {
					if(el.val() == "" || el[0].options[el[0].selectedIndex].innerHTML == "" && el.val() == 0) {
						el.removeClass("notempty");
					}
					else {
						el.addClass("notempty");
					}
				}
				else if(el.val() == "") {
					el.removeClass("notempty");
				} else {
					el.addClass("notempty");
				}

				// register onchange listener
				el.change(function() {
					var t = $(this);
					// If select also check for value of "0"
					if(t.is("select")) {
						if(t.val() == "" || t[0].options[t[0].selectedIndex].innerHTML == "" && t.val() == 0) {
							t.removeClass("notempty");
						}
						else {
							t.addClass("notempty");
						}
					}
					else if(t.val() == "") {
						t.removeClass("notempty");
					} else {
						t.addClass("notempty");
					}
				});
			});
		},

		/*
		 * Implement visibility toggle for Treeview element
		 * Searches only for <div>
		 *
		 * Demo in "demo_multimediagalerie.html"
		 */
		impl_treeview: function() {
			$("div.node-label").click(function() {
				var parentn = this.parentNode;
				parentn.className = (parentn.className.indexOf('node-expanded') >= 0 ?
				parentn.className.replace('node-expanded', 'node-collapsed') :
				parentn.className.replace('node-collapsed', 'node-expanded'));
			});
		},

		/*
		 * Cleans up the DOM
		 */
		cleanup: function() {
			AUBIGL = null;
		},

		/*
	     * Sets a cookie
	     */
	    set_cookie: function(name,value,days) {
	      if (days) {
	        var date = new Date();
	        date.setTime(date.getTime()+(days*24*60*60*1000));
	        var expires = "; expires="+date.toGMTString();
	      }
	      else var expires = "";
	      document.cookie = name+"="+value+expires+"; path=/";
	    },

	    /*
	     * Gets cookie
	     */
	    get_cookie: function(name) {
	      var nameEQ = name + "=";
	      var ca = document.cookie.split(';');
	      for(var i=0;i < ca.length;i++) {
	        var c = ca[i];
	        while (c.charAt(0)==' ') c = c.substring(1,c.length);
	        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	      }
	      return null;
	    },

	    /*
	     * Modul status
	     */
	    modul_set_cookie: function(par) {
		    // Remember status in cookie
		    var cls = par.attr("class");
		    var page_id = cls.indexOf(' page-id');

		    // Only if there IS a page_id (legacy application dont have these)
		    if(page_id > -1) {
		    	// HTML must be like class="modul mod-something ignored..."
			    var val = cls.split(" ")[1];
			    var c = AUBIGL.get_cookie("mod_"+val);

		    	page_id = cls.substring(page_id+1);
		    	var leer = page_id.indexOf(" ");
		    	if(leer > -1) {
		    		page_id = page_id.substring(0,leer);
		    	}
		    	page_id = page_id.replace("page-id_","");

		    	if(c != null && c.indexOf(page_id) > -1) {
				  // Remove from cookie
			      AUBIGL.set_cookie('mod_'+val,c.replace(page_id,'').replace(',,',','));
			    } else {
			      // Append to cookie
			      AUBIGL.set_cookie('mod_'+val,(c==null||c==''?'':c+",")+page_id);
			    }
		    }
	    },

        _ivw: function(ivwneu) {
            var ivw = $("#content_ivw_pixel");
            if(ivw.length == 1) {
                var ivw_src = ivw.attr("src").replace(/d=(.*)/,"d="+Math.random());
                if(typeof ivwneu != "undefined") {
                    ivw_src = ivw_src.replace(/CP\/(.*);/,"CP/"+ivwneu+";");
                }
                ivw.attr("src",ivw_src);
            }
        },

        _ga: {
            path: "",
            track: function(path, tracker) {
                path = path || window.google_tracking;
                this.path = path;
                tracker = (typeof tracker != "function")?this.by_urchin_v1:tracker;
                this.pretrack();
                tracker(path);
                this.posttrack();
            },
            pretrack: function() {},
            posttrack: function() {},
            /* TRK Functions */
            by_urchin_v1: function(path) {
                urchinTracker(path);
            },
            by_urchin_v2: function(path) {
                pageTracker._trackPageview(path);
            }
        },

        _ct: {
            current: "",
            target: "",
            ct_str: "",
			tags: [],
            ct_url: function(url) {
                return (typeof url == "undefined")?"":url.replace(/www\.autobild\.de[\/]?$/,"www.autobild.de/index.html")
                      .replace(/http(s)?:\/\//,"")
                      .replace(/\?.*/,"")
                      .replace(/\./g,"_")
                      .replace(/.*:.*/,"")
                      .replace(/#.*$/,"")
                      .replace(/[# \/]{1}$/,"");
            },
            ct_complete: function(current, target, tags) {
                var complete = "/"+target+"/QUELLE/"+current;
				if(tags.length > 0) {
					complete += "/CTTAG/"+tags.join("/");
				}
				return complete;
            },
			ct_tagging: function(dom_el) {
				var cttag = [];
				if(dom_el.className.indexOf("cttag-") > -1) {
					cttag = dom_el.className.match(/([ ]{1}|^)cttag-([a-zA-Z0-9-_]+)([ ]{1}|$)/)[2];
					cttag = cttag.split("_");
				}
				return cttag;
			},
            track: function(dom_element) {
                var follow_link = true;
                this.current = this.ct_url(document.location.href);
				this.tags = this.ct_tagging(dom_element);
                this.target = this.ct_url(dom_element.href||dom_element.action);
                this.target = (this.target=="")?this.current:this.target;
                this.ct_str = this.ct_complete(this.current, this.target, this.tags);
                follow_link = this.pretrack(dom_element);
                if(this.current != this.target) AUBIGL._ga.track(this.ct_str, AUBIGL._ga.by_urchin_v2);
                follow_link = this.posttrack(follow_link);
                return (typeof follow_link == "undefined")?true:follow_link;
            },
            pretrack: function(dom_element) { return true; },
            posttrack: function(follow_link) { return follow_link; }
        }
	}
}

/*
 * Toggles Tabs of a Module Block
 * Must be global, because it is referenced in the GWI HTML :(
 *
 * Module ids are "mod-MODULENAME-tab-INDEX"
 */
function activateModuleTab(strModName, intTabIndex) {
	// Set up cache fuer this selector
	if(isu(AUBIGL.cstore[strModName])) {
		AUBIGL.cstore[strModName] = $("li[id*='"+strModName+"-tab']");
	}

	// Deactivate all Tabs
	AUBIGL.cstore[strModName].each(function() {
		this.className = this.className.replace(/active/,"idle");
	});

	// Highlight current
	var current = $("#"+strModName+"-tab"+intTabIndex);
	current.attr("class",current.attr("class").replace(/idle/,"active"));

	// Hide all content-divs except current selected tab
	// Using ID is way faster than using classnames
	for(var i=1; i <= AUBIGL.max_tabs; i++) {
		$("#"+strModName+"-tabcontent"+i).hide();
	}

	// Show the content of the selected tab
	$("#"+strModName+"-tabcontent"+intTabIndex).show();
}

function switchTabMenu(tab_group_name, tab_id_prefix, tab_id_postfix, active_tab)
{
	// Zuruecksetzen aller Tabs
	last_tab = 0;
	var node = document.getElementById(tab_group_name).firstChild;
	while (node != null)
	{
		if (node.nodeName == "LI")
		{
			node.className = '';
			last_tab++;
		}
		node = node.nextSibling;
	}

	tab_group_class = 'tabs3';
	last_tab_class = 'tabs3-last';
	first_tab_class = 'tabs3-first';
	active_tab_class = '';
	previous_tab_class = '';

	if (active_tab == last_tab)
	{
		last_tab_class = 'tabs3-last-active';
	}
	else if (active_tab == 1)
	{
		first_tab_class = 'tabs3-first-active';
		tab_group_class = 'tabs3 tabs3-first-left-active';
	}

	if (active_tab < last_tab && active_tab > 1)
	{
		active_tab_class = 'tabs3-active2';
	}


	if (active_tab > 1)
	{
		previous_tab_class = 'tabs3-active';
	}

	document.getElementById(tab_group_name).className = tab_group_class;
	document.getElementById(tab_id_prefix + last_tab).className = last_tab_class;
	document.getElementById(tab_id_prefix + '1').className = first_tab_class;

	if (active_tab_class.length > 0)
	{
		document.getElementById(tab_id_prefix + active_tab).className = active_tab_class;
	}

	if (previous_tab_class.length > 0)
	{
		document.getElementById(tab_id_prefix + (active_tab - 1)).className = previous_tab_class;
	}

	for (i = 1; i <= last_tab; i++)
	{
		document.getElementById(tab_id_prefix + i + tab_id_postfix).className = 'tabs3_hidden';
	}
	document.getElementById(tab_id_prefix + active_tab + tab_id_postfix).className = 'tabs3_show';

}

/*
 * Global Init Function
 *
 */
function gl_init() {
	// Register hook to initialize AUBIGL object
	$(document).ready(function() {
		AUBIGL.init_ready();
	});
}

/*
 * Shortcut to "typeof undefined"
 */
if(typeof isu == "undefined") {
	function isu(obj) {
	   return (typeof obj == "undefined");
	}
}

// Call GL INIT the first time
gl_init();