/***  made with love by smarter-ecommerce.com ***/

//ClusterNames[0] = new Object();
//ClusterNames[0]["id"] = "products";
//ClusterNames[0]["name"] = "smec Products";
//ClusterNames[1] = new Object();
//ClusterNames[1]["id"] = "smec Tags";
//ClusterNames[1]["name"] = "smec Tags";
//ClusterNames[2] = new Object();
//ClusterNames[2]["id"] = "smec";
//ClusterNames[2]["name"] = "smec Corporate";
//ClusterNames[3] = new Object();
//ClusterNames[3]["id"] = "blog";
//ClusterNames[3]["name"] = "smec Blog";
//ClusterNames[4] = new Object();
//ClusterNames[4]["id"] = "downloads";
//ClusterNames[4]["name"] = "smec Downloads";
ClusterNames = new Object();
ClusterNames["products"] = "smec Products";
ClusterNames["smec Tags"] = "smec Tags"; 
ClusterNames["smec"] = "smec Corporate";
ClusterNames["blog"] = "smec Blog";
ClusterNames["downloads"] = "smec Downloads";
//ClusterNames["twitter"] = "smec Twitter";


jQuery.fn.extend({
	smecsearch: function(url, options) {
		options = jQuery.extend({
			url: url,
			delay: 500,
			fields: 'title,uri',
			type: 'overview',
			dataType: 'jsonp',
			clusterlink: function(clusterId, query, simGroup) {
				return String.format(options.detailsUrl, encodeURIComponent(query), encodeURIComponent(clusterId), encodeURIComponent(simGroup) );
			},
			highlight: function(value, terms) {
				var splitted = terms.split(/\s+/)
				var pattern = ''
				for (var i=0; i< splitted.length; i++) {
					if (i > 0) pattern += '|';
					pattern += splitted[i].replace(/[^-a-zA-Z0-9öäüÖÄÜß:]+/gi, '')
					
				}
				return value.replace(new RegExp('(' + pattern + ')', 'gi'), "<strong>$1</strong>");
			},
			applyAfterEffects: function(){} 
		}, options);

	    return this.each(function() {
			new $.SmecSearch(this, options);
		});
	}
});


$.SmecSearch = function(input, options) {
	var $input = $(input);
	var needsInit = true;
	var searchContainer;
	var lastKeyPressCode;
	var timeout;
	var previousValue = "";
	var active = -1;
	var closer = $('<div/>').attr('class', 'search_x');
	var header = $('<div/>').attr('class', 'overlaybox_body');
	var footer = $('<div/>').attr('class', 'overlaybox_bottom');
	var KEY = {
			UP: 38,
			DOWN: 40,
			DEL: 46,
			TAB: 9,
			RETURN: 13,
			ESC: 27,
			COMMA: 188,
			PAGEUP: 33,
			PAGEDOWN: 34,
			BACKSPACE: 8
	};	
	
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		if(needsInit) {
			searchContainer= $('<div/>');
			if (! $.browser.opera) searchContainer.hide();
			needsInit = false;
			var offset = $(input).offset();
			
			searchContainer.appendTo(document.body).attr('class', 'searchbox');
			searchContainer.css({
				top: offset.top + input.offsetHeight -10,
				left: offset.left - 13,
				position: 'absolute',
				'z-index': 100
			});
		}
		switch(event.keyCode) {
			case KEY.ESC:
				hideContainer();
				break;
			case KEY.RETURN:
				if (active >= 0) {
					var li = $("div.searchbox dd.ac_over")[0];
					if (li) {
						selectItem(li);
					}
				} else {
					if ($input.val().length >= 3) {
						document.location.href = "search.php?q="+encodeURIComponent($input.val());
					}
				}
				break;
			case  KEY.DEL, KEY.BACKSPACE :
				if($input.val() == '') {
					hideContainer(); break;
				}
				if ($input.val().length >= 5) {
					clearTimeout(timeout);
					timeout = setTimeout(onChange, options.delay);
				}
				break;
			case KEY.TAB:
				break;
			case KEY.UP: // up
				//e.preventDefault();
				moveSelect(-1);
				break;
			case KEY.DOWN: // down
				//e.preventDefault();
				moveSelect(1);
				break;
			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
		
		function onChange() {
			if($input.val() != '' && previousValue != $input.val() && $input.val().length>=3) {
				previousValue = $input.val();
				//smeccookie.setCookie(smeccookie.COOKIE_NAME, $input.val());
				request(buildUrl(), {query:$input.val(),type:options.type});
			}
		}
		
		function request(url, params) {
			$.getJSON(url, params, formatResult);
		}
		
		function buildUrl() {
			var callback ='';
			if(options.dataType == 'jsonp') {
				callback = '&callback=?';
			}
			return options.url + '?fields=' + options.fields + callback;
		}
		
		String.format = function(text) {
		    if ( arguments.length <= 1 ) {
		        return text;
		    }
		    var tokenCount = arguments.length - 2;
		    for( var token = 0; token <= tokenCount; token++ ) {
		        text = text.replace( new RegExp("\\{" + token + "\\}", "gi" ),arguments[ token + 1 ] );
		    }
		    return text;
		};
		
		function formatResult(data){
			var totalHits = data.result.totalHits;
			
			searchContainer.html('').append(closer);
			//closeDiv.click(hideContainer);
			var isFirst=true;
			
			if(data.result.totalHits > 0) {
	            var clusters = data.result.clusters;
	            var list = $('<dl/>');
						
				//for (var i = 0; i < ClusterNames.length; i++) {
  				//	for (var Eigenschaft in Mitarbeiter[i])
    			//		document.write("<dd>" + Eigenschaft + ": " + Mitarbeiter[i][Eigenschaft] + "<\/dd>");
				//}


	            for(var i = 0; i < clusters.length; i++) {
	                var clusterResults = clusters[i].results;

	                if(clusterResults.length > 0) {
	                    var clusterName = clusters[i].name;

						if (clusterName == 'global') continue;
						
	                    list.append(
	                        $('<dt/>').append(
	                            $('<a/>').attr('href', '').text(ClusterNames[clusterName])
	                        )
	                    );

	                    for(var j = 0; j < clusterResults.length; j++) {
	                        var title = clusterResults[j].title;
	                        var uri = clusterResults[j].uri;
	                        list.append(
	                            $('<dd/>').attr('class', j == 0 ? 'overlay_item_first' : 'overlay_item_following').append(
	                                $('<a/>').attr('href', uri).text(constrain(title, 35))
	                            )
	                        );
	                    }
	                }
	            }
				
				header = $('<div/>').attr('class', 'overlaybox_body').append(list);
	            searchContainer.append(header).append(footer);
				$("div.search_x").click(function(){
					$input.attr("value", "");
					hideContainer();
				});
	        
				searchContainer.show();
				options.applyAfterEffects.call(this);
			} else {
				hideContainer();
			}
		}
		
		function hideContainer() {
			searchContainer.html('').hide();
			options.applyAfterEffects.call(this);
		}
		
		function constrain(str, n) { 
		  	var words = str.split(' '); 
			var resultstr = '';
			var wordCount = words.length; 
			for(var i = 0; i < wordCount; i++ ){ 
			    if((resultstr + words[i] + ' ').length >= n) { 
			    	resultstr += '...'; 
			    	break; 
			    }  
			    resultstr += words[i] + ' '; 
			} 
			return resultstr; 
		}

	 	function moveSelect(step) {
			var lis = $("div.searchbox dd")
			if (!lis) return;

			active += step;

			if (active < 0) {
				active = 0;
			} else if (active >= lis.size()) {
				active = lis.size() - 1;
			}

			lis.removeClass("ac_over");

			$(lis[active]).addClass("ac_over");

			// Weird behaviour in IE
			// if (lis[active] && lis[active].scrollIntoView) {
			// 	lis[active].scrollIntoView(false);
			// }

		};
		
		function selectItem(li) {
			link_target = $("a", li).attr("href");
			document.location.href = link_target;
		};
	});
};

/***  made with love by smarter-ecommerce.com ***/
jQuery.fn.extend({
	smectags: function(url, options) {
		options = jQuery.extend({
			url: url,
			anchorElement: $('body'),
			tagsize: 1,
			delay: 0,
			fields: 'title,uri',
			type: 'overview',
			dataType: 'jsonp',
			applyAfterEffects: function(){}
		}, options);

	    return this.each(function() {
			new $.SmecSearchRequest(this, options);
		});
	}
});

$.SmecSearchRequest = function(element, options) {
    var $links = $(element);
	var tagElement = null;
    var url = options.url;
	var query = '';
    var type = options.type;
    var dataType = options.dataType;
    var fields = options.fields;
    var tagsize = 1;
	var tagname = '';
	var tagref = '/';
    var anchorElement = options.anchorElement;
    //var sessionId = options.sessionId;
	
	tagElements = $links.find('span span');
	tagElements.bind('mouseover', function() {
		var hover_intent;		
		$(this).bind('mouseout', function() {
			try{
				clearTimeout(hover_intent);
			} catch(e){};
		});
	
		if ($('div.cloudmenu')) $('div.cloudmenu').remove();
		
		element = $(this).parent().parent();
		tagElement = $(this);
		query = element.attr('rel') || options.query;
		tagname = tagElement.text() || options.tagname;
		tagsize = tagElement.attr('style').replace(/font-size: *(\d+\.?\d*)em;?$/ig, '$1') || options.tagsize;
		tagref  = element.attr('href') || options.tagref;
		hover_intent = setTimeout(function() {request(buildUrl(), {query:query, type:type})}, 150);
		//request(buildUrl(), {query:query, type:type});
		
	});	

    this.doSmecSearch = function() {
        return request(buildUrl(), {query:query, type:type});
    }

    function buildUrl() {
        var callback='';
        if(dataType == 'jsonp') {
            callback = '&callback=?';
        }
        return url + '?count=4&clusters=de-smecTags,de-products&fields=' + fields + callback;
    }

    function request(url, params, options) {
    	$.getJSON(url, params, function(data) {
            var smecformatter = new $.SmecSearchFormatter(data);
            smecformatter.tagOverlayHtml(anchorElement, tagElement, tagsize, tagname, tagref);
        });
    }
}

$.SmecSearchFormatter = function(data) {
    var json = data;

    this.tagOverlayHtml = function(element, tagElement, tagsize, tagname, tagref) {
        if(json.result.totalHits > 0) {
            var clusters = json.result.clusters;
            var list = $('<dl/>');

            for(var i = 0; i < clusters.length; i++) {
                var clusterResults = clusters[i].results;

                if(clusterResults.length > 0) {
                    var clusterName = clusters[i].name;

					if (clusterName == 'global') continue;
						
                    list.append(
                        $('<dt/>').append(
                            $('<a/>').attr('href', '').text(ClusterNames[clusterName])
                        )
                    );

                    for(var j = 0; j < clusterResults.length; j++) {
                    	var title = clusterResults[j].title;
                        var uri = clusterResults[j].uri;
                        list.append(
                            $('<dd/>').attr('class', j == 0 ? 'overlay_item_first' : 'overlay_item_following').append(
                                $('<a/>').attr('href', uri).text(constrain(title, 35))
                            )
                        );
                    }
                }
            }

            $(element).append(
                $('<div/>').attr('class', 'overlaybox cloudmenu').append(
                    $('<div/>').attr('class', 'overlaybox_tab').append(
                        $('<span/>').attr('class', 'tab').append(
	                        $('<a/>').attr('href', tagref).append(
                            	$('<span/>').attr('style', 'font-size: ' + tagsize + 'em;').text(tagname)
							)
                        )
                    )
                ).append(
                    $('<div/>').attr('class', 'overlaybox_body overlaybox_body_tagcloud').append(list)
                ).append(
                    $('<div/>').attr('class', 'overlaybox_bottom')
                )
            );

			$("div.overlaybox_tab").mouseleave(function(event){
				moved_to = $(event.relatedTarget);
				if (moved_to.is("div.overlaybox_body") || moved_to.is("div.overlaybox_body dl")) {
					$("div.cloudmenu").mouseleave(function(event){
						$('div.cloudmenu').remove();
					});
				} else {
					$('div.cloudmenu').remove();
				}
			});

			showOverlay(tagElement);
        }

		function constrain(str, n) { 
		  var words = str.split(' '); 
		  var resultstr = '';
		  var wordCount = words.length; 
		  for(var i = 0; i < wordCount; i++ ){ 
		    if((resultstr + words[i] + ' ').length >= n) { 
		      resultstr += '...'; 
		      break; 
		    }  
		    resultstr += words[i] + ' '; 
		  } 
		  return resultstr; 
		}
    }

	function showOverlay(element) {
		left_tab = Math.round($("div.cloudmenu div.overlaybox_tab span.tab span").position().left);
		top_tab  = Math.round($("div.cloudmenu div.overlaybox_tab span.tab span").position().top);
		
		left_tag = $(element).position().left;
		top_tag  = $(element).position().top;
		
		position = absolutePosition(element);
		left_tag = position[0];
		top_tag  = position[1];
		
		/*if (left_tag > 528) {
			$("div#overlay_"+ id +" div.overlaybox_tab").css("float", "right").css("float", "right").css("padding", "0 13px 0 0").css("background-image", "url(images/overlay_tab_left_inverted.png").css("background-position", "top right");
			$("div#overlay_"+ id +" div.overlaybox_tab span.tab").css("float", "right").css("margin", "0 0 0 -17px").css("padding", "0.6em 13px 0.1em 30px").css("background-image", "url(images/overlay_tab_right_inverted.png").css("background-position", "top left");
		}*/
		
		msie7 = false;
		jQuery.each(jQuery.browser, function(i, val) {
		  if(i=="msie" && jQuery.browser.version.substr(0,1)=="7")
		     msie7 = true;
		});
		
		if (!overlay_visible()) {
			$("div.cloudmenu").css("top", (top_tag - top_tab - 1) + "px");
			$("div.cloudmenu").css("left", (left_tag - left_tab - (msie7 ? 1 : 0)) + "px");
		}
	}
	
	function absolutePosition(target) {
		offset = [0.0, 0.0];

		tNode = target[0] || target;
	    while (tNode.nodeName != "BODY" && tNode.nodeName != "HTML") {
	    	offset[0] += tNode.offsetLeft;
	        offset[1] += tNode.offsetTop;
	        tNode = tNode.offsetParent;
		}

	    return offset
	}

	function overlay_visible() {
		$("div.cloudmenu").each(function() {
	    	left = parseFloat($(this).css("left"));
	    	if (left > -9999) {
	    		return true;
	    	}
	    	return false;
		});
	}
}

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

$(document).ready(function() {	
	$("a.tag_link").smectags('http://s.smecsearch.com', {anchorElement: $('div.wrapper')});
	$("input#searchterm").smecsearch('http://s.smecsearch.com');
	
	$("a#show_salesintelli").mouseenter(function(){
		$("div#overlay_sales").show();
	}).mouseleave(function(event){
		moved_to = $(event.relatedTarget);
		if (moved_to.is("div#overlay_sales")) {
			// noop
		} else {
			$("div#overlay_sales").hide();
		}
	});
	
	$("div#overlay_sales").mouseleave(function(){
		$("div#overlay_sales").hide();
	})
	
	$("a.bar img").mouseover(function() {
		$(this).attr("src", $(this).attr("src").replace(/\.png/ig, "_active.png"));
	})
	$("a.bar img").mouseleave(function() {
		$(this).attr("src", $(this).attr("src").replace(/_active\.png/ig, ".png"));
	})

	$("a.share_this").click(function(){
		id = extractId($(this).attr("id"));
		if ($("div.shares div.share_this div#overlay_share_" + id).is(":visible")) {
			$("div.shares div.share_this div#overlay_share_" + id).hide();
			$("a#share_this_" + id + " img").attr("src", "/images/button_share_this.png");
		} else {
			$("div.shares div.share_this div#overlay_share_" + id).show();
			$("a#share_this_" + id + " img").attr("src", "/images/button_share_this_active.png");
		}
	})
	
	var register_counter = 0;
	$("a.register_link").each(function(){
		original_url = $(this).attr("href");
		$(this).attr("href", "/index.php/site/lead_form?url=" + original_url);
	});
	
	$("h5#commentsheadline_closed a").click(function(){
		$("h5#commentsheadline_closed").hide();
		$("h5#commentsheadline_opened").show();
		$("div#comment_form_container").show();
		$("div#comment_form_container_closer").show();
	});
	
	$("a.open_dialog").click(function(){
		if ($("div.download_prompt").is(":visible")) {
			$("div.download_prompt").hide();
		} else {
			$("div.download_prompt").show();	
		}
	});

	$("a#close_dialog, a#cancel_dialog").click(function(){
		if ($("div.download_prompt").is(":visible")) {
			$("div.download_prompt").hide();
		}
	});	
	
	$("form#download_form").submit(function(){
		if ($("div.download_prompt").is(":visible")) {
			$("div.download_prompt").hide();
		}
	});
	
	$(function() {
		$('.lightbox').lightBox({fixedNavigation:true});
	});
	
	/* SIE Box by holger */
	$(".rollover").css({'opacity':'0'});
	$('.sie-imagemap a').hover(function() {
			$(this).children('.rollover').stop().fadeTo(500, 1);
		},
		function() {
			$(this).children('.rollover').stop().fadeTo(500, 0);
		}
	)
});

function extractId(string) {
    return string.replace(/.*_(\d+)$/ig, '$1');
}

/*
    requires bitly javascript api:
    http://code.google.com/p/bitly-api/wiki/JavascriptClientApiDocumentation
*/

var TweetAndTrack = {};
TweetAndTrack.open = function(targ, url) {
    var child_spans = targ.getElementsByTagName('span');
    if (child_spans && child_spans.length > 0) {
        var msg = child_spans[0].innerHTML.toString();
    } else {
        msg = '';
    }
    
    var callback_name = url.replace(/\W/g, '');
    BitlyCB[callback_name] = function(data) {
        var result = TweetAndTrack.popResult(data);
        var tweet_url = "http://twitter.com/home?status=" + encodeURIComponent(msg + " " + result.shortUrl + " - @smec");
        TweetAndTrack.newWindow(tweet_url, "600", "400");
    };
    BitlyClient.call('shorten', {'longUrl': url, 'history': '1'}, 'BitlyCB.' + callback_name);
    // BitlyClient.shorten(url, 'BitlyCB.' + callback_name);
    return false;
};

TweetAndTrack.popResult = function(data) {
    // Results are keyed by longUrl, so we need to grab the first one.
    for (var r in data.results) {
        return data.results[r];
    }
};

TweetAndTrack.newWindow = function(url, width, height) {
  var a = function() {
    if(!window.open(url,'t','scrollbars=yes,toolbar=1,resizable=1,status=1,width='+width+',height='+height))document.location.href=url;
  };
  
  if( /Firefox/.test(navigator.userAgent)) {
    setTimeout(a,0);
  } else {
    a();
  }
};
