function showAnchor(anchor) {
	var loc = anchor;
	if (loc.match('#')) { // validate the anchor
		  // try to find the anchor and click it
		  var myAnchor = loc.split('#')[1];
		  // we only click the referenced anchor if it is invisible -> therefore this method is called show and not toggle ;-)
		  if (!$('a.faq[name='+myAnchor+']').parent().next('div').is(":visible")) {
			  $('a.faq[name='+myAnchor+']').click();
		  }
	} 
}

function toggleUrlAnchor() {
	var loc = document.location.toString();
	if (loc.match('#')) { // does the URL contain an anchor
		  // try to find the anchor and click it
		  var myAnchor = loc.split('#')[1];
		  $('a.faq[name='+myAnchor+']').click();
		  $('a.setup-guide-section[name='+myAnchor+']').click();
	} 
}

function inPageAnchorTrigger() {
	$('a').each(function(i){
		var myhref = $(this).attr('href');
		if (myhref != null) {
			var mychar = myhref.charAt(0);
			if (mychar != null && mychar == '#') {
				$(this).bind('click', function(event) {
					showAnchor(myhref);
				});
			}
		}
	});
}

function startOverlayRotation() {
	$(".ipad_overlays a").lightBox({
		//imageBtnPrev: '/img/button/lb_prev.png',
		//imageBtnNext: '/img/button/lb_next.png',
		containerResizeSpeed: 350
	   });
	;
	$(".iphone_overlays a").lightBox({
		//imageBtnPrev: '/img/button/lb_prev.png',
		//imageBtnNext: '/img/button/lb_next.png',
		containerResizeSpeed: 350
	   });
	;
	
	$(".free_overlays a").lightBox({
		//imageBtnPrev: '/img/button/lb_prev.png',
		//imageBtnNext: '/img/button/lb_next.png',
		containerResizeSpeed: 350
	   });
	;
	
	$(".galaxy_overlays a").lightBox({
		//imageBtnPrev: '/img/button/lb_prev.png',
		//imageBtnNext: '/img/button/lb_next.png',
		containerResizeSpeed: 350
	   });
	;
	
	$(".nexus_overlays a").lightBox({
		//imageBtnPrev: '/img/button/lb_prev.png',
		//imageBtnNext: '/img/button/lb_next.png',
		containerResizeSpeed: 350
	   });
	;
	
	$(".desktop_rdp_overlays a").lightBox({
		containerResizeSpeed: 350
	   });
	;
	
	$(".ipad_overlays").cycle({
		slidePause: 5000});
	$(".iphone_overlays").cycle({
		slidePause: 5000});
	$(".free_overlays").cycle({
		slidePause: 5000});
	$(".galaxy_overlays").cycle({
		slidePause: 5000});
	$(".nexus_overlays").cycle({
		slidePause: 5000});
	$(".desktop_rdp_overlays").cycle({
		slidePause: 5000});
}

function initFaq() {
	$('a.faq').each(function(i){
		$(this).parent().next('div').hide();
		$(this).bind('click', function(event) {
					clicked = $(this);
					clicked.parent().next('div').toggle();
					arrowspan = clicked.find('span');
					arrowspan.toggleClass('arrow_right arrow_down');
				}
			);
	});
	$('a.faq').each(function(index,element) {
		var $element = $(element);
		if ($element.find('.arrow_right').length == 0) {
			$element.prepend('<span class="arrow_right"></span>');
		}
	});
	inPageAnchorTrigger();
};

function initSetupGuide() {
	$('a.setup-guide-section').each(function(i){
		$(this).parent().next('div').hide();
		$(this).bind('click', function(event) {
					clicked = $(this);
					clicked.parent().next('div').toggle();
					arrowspan = clicked.find('span');
					arrowspan.toggleClass('arrow_right arrow_down');
				}
			);
	});
	$('a.setup-guide-section').prepend('<span class="arrow_right">');
	inPageAnchorTrigger();
};

(function($) {
	function go(images,opts) {
	    if (opts.busy) return;
	    var p = images[0].parentNode, curr = images[opts.currSlide], next = images[opts.nextSlide];
	    if (p.cycleTimeout === 0) 
	        return;
	    if (!p.cyclePause) {
	        var after = function() {
	            if ($.browser.msie)
	                this.style.removeAttribute('filter');
	        };
	
	        if (opts.nextSlide != opts.currSlide) {
	            opts.busy = 1;
	            $.fn.cycle.custom(curr, next, opts, after);
	        }
	        var roll = (opts.nextSlide + 1) == images.length;
	        opts.nextSlide = roll ? 0 : opts.nextSlide+1;
	        opts.currSlide = roll ? images.length-1 : opts.nextSlide-1;
	    }
	    if (opts.slidePause)
	        p.cycleTimeout = setTimeout(function() { go(images,opts) }, opts.slidePause);
	};


	$.fn.cycle = function(options) {
		return this.each(function() {
			options = options || {};
			this.cyclePause = 0;
			var $container = $(this);
			$container.css('overflow','hidden');
			var $slides = $container.children().find('img')
			var images = $slides.get();
			if (this.slidePause) clearTimeout(this.slidePause);
			var slidePause = options.slidePause ? options.slidePause : 200;
			var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $container.data() : {});
			opts.busy = 0;
			opts.slideCount = images.length;
	        opts.currSlide = 0;
	        opts.nextSlide = 1;
	        opts.slidePause = slidePause;
	        var width = $container.width();
	        opts.leftBefore = 0;
			opts.animIn	  = { left: 0 };
			opts.animOut  = { left: -width };
			$slides.hide();
			$($slides[0]).show();			
	        this.cycleTimeout = setTimeout(function() {
	                go(images,opts)
	            }, opts.slidePause);
		});
	}


	$.fn.cycle.custom = function(curr, next, opts, cb) {
	  	   $(next).css('left',$(next).width());
		   $(next).show();
		   $(next).animate(opts.animIn, 600, null, function() {});
		   $(curr).animate(opts.animOut, 600, null, function() {$(curr).hide(); opts.busy=0;});
		  
	};

})(jQuery);	

/*
 * faq search feature
 */

var faqSearchIndex = 0;

// internal function to search faq entries 
function faqSearch(product,queryText,currentSearchIndex,onResult) {
	
	var data = $.toJSON({
							header:				{ protocolVersion: 1 },
							product:			product,
							queryText:			queryText
						});
	$.ajax(	{
				url:			'/services/faq-result/query',
				data:			data,
				dataType:		'json',
				error:			function(jqXHR,textStatus,errorThrown) {
								},
				success:		function(data,textStatus,jqXHR) {
									if (currentSearchIndex == faqSearchIndex)
										onResult(data);
								},
				cache:			false,
				processData:	false,
				type:			'POST',
				contentType:	'application/json; charset=UTF-8'
			});
}

// faq initializer, use this function to allow for faq searches on a website
// @param	productName			specifies the product to query for
// @param	$searchField		a jquery object containing a text element which can be monitored for keyup
// @param	$areaDynamic		the jquery object of a <ul> element containing the area where the <li> entries for the faqs are inserted
//@param	$elementToShow		a jquery object containing elements which are shown as soon as a successful search result is received and which are hidden if the $searchField does not contain content
// @param	$elementToHide		a jquery object containing elements which are hidden as soon as a successful search result is received and which are shown if the $searchField does not contain content
// @param	noResultsMessage	a message to display if there are no results, can be the empty string if such a message is not desired. Message must contain <li> tags because it is located in the $areaDynamic <ul>
function initFaqSearch(productName,$searchField,$areaDynamic,$elementToShow,$elementToHide,noResultsMessage) {
	
	$elementToHide.show();
	$areaDynamic.hide();
	$elementToShow.hide();

	$searchField.unbind('keyup');
	$searchField.keyup(function() {
		var content = $searchField.val();
		if (content.length > 0) {
			// query for results
			faqSearch(productName,content,++faqSearchIndex,function(data) {
				
				$elementToHide.hide();
				$areaDynamic.show();
				$elementToShow.show();
				$areaDynamic.html('');
				
				if (data.entries.length > 0) {

					$.each(data.entries,function(index,entry) {
						if (entry.rank > 0.1) {
							var entryHtml = '';
							entryHtml += '<li class="faq" style="margin-bottom: 16px"><h3><a class="faq" name="' + entry.hashTag + '">' + entry.title;
							//if (entry.rank !== "undefined")
							//	entryHtml += " (" + entry.rank + ")";
							entryHtml += '</a></h3><div>';
							entryHtml += entry.htmlBody;
							entryHtml += '</div></li>';
							$areaDynamic.append(entryHtml);
						}
					});
					initFaq();
				} else {
					$areaDynamic.html(noResultsMessage);
				}
			});
			
		} else {
			$elementToShow.hide();
			$elementToHide.show();
			$areaDynamic.hide();
		}
	});
	
}

