$(function()
{
	$('div.entries > div').equalizeCols();
	
	//$('#press-images div.item').equalizeCols();
	
	$('#press-images div.item p.press a').click(function()
	{
		window.open($(this).attr('href'));
		return false;
	});
	
	var $nav_news_link = $('ul#nav li a.news');
	var $nav_prod_link = $('ul#nav li a.ps');
	
	$("a.fancylink").fancybox({
		'titlePosition'	: 'inside'
	});
	
	
	if ($('#map').size())
	{
		Map.init();
	}
	
	$('p.print a').click(function()
	{
		window.print();
		return false;
	});	
	
		
	NavDropDowns.init_load_product_samples();
	//NavDropDowns.toggle_dropdown($nav_news_link); // Init behavior for news link
	//NavDropDowns.toggle_dropdown($nav_prod_link); // Init behaviro for product-samples link
	
	Video.init();
	
	Entries.init();
	
	ProdSample.init();
	
	Filter.init();
	
	NewWindow.init();
	
	Newsletter.init();
	
	ContactCards.init();
	
	//FlashStart.resize();
});

$(window).resize(function()
{
	//FlashStart.resize();
});

var FlashStart =
{
	resize:function()
	{
		var $window = $(window);
		var $flash = $('#flashcontent');
		
		var $content_and_container = $flash.add('#content');
		
		var hPadding = 20;
	
		var ww = $(window).width() - (hPadding*2);
		var wh = $(window).height();

		var fw = $flash.width();
		var fh = $flash.height();
		
		var fpos = $flash.offset();
		
		wh -= fpos.top;
		
		if ( ww < fw ) // if window is narrower than flash
		{
			$content_and_container.width( Math.max(ww,850)-2 );
			$flash.attr("width", Math.max(ww,850)-2);
		}
		else
		{
			$content_and_container.width( Math.min(ww,1260)-2 );
			$flash.attr("width", Math.min(ww,1260)-2);
		}
		
		if ( wh < fh )
		{
			$content_and_container.height( Math.max(wh,600) );
			$flash.attr("height", Math.max(wh,600) );
		}
		else 
		{
			$content_and_container.height( Math.min(wh,700) );
			$flash.attr("height", Math.min(wh,700) );
		}
		
	}
}

var ContactCards =
{
	init:function()
	{
		if ($.browser.msie && parseInt($.browser.version) == 7) // IE 7 cant handle z-index so fuck it
		{
			return false;
		}
		
		for (var c in contacts)
		{
			$('p, li, cite').contactcard(c);
		}

		//$('p, li, cite').contactcard('fredrik blomquist');

		$('span.contactcard').hover(function()
		{
			$(this).append('<span class="info">' + contacts[$(this).text()][1] + '</span>');
		},
		function()
		{
			$(this).find('span.info').remove();
		});
	}
}

var NewWindow =
{
	init:function()
	{
		var $links = $('a[href^="http://"], a[href^="https://"], a[href$=".pdf"], #press ul.listing li a');

		$links.click(function()
		{	
			var $this = $(this);
			var href = $this.attr('href');

			if (href.indexOf('netoptions.se') == -1 && href.indexOf('bizwizard.dev') == -1)
			{
				window.open(href);
				return false;
			}
		});
	}
};

var Filter =
{
	init:function()
	{
		$filters = $('div.filter');
		
		$filters.each(function()
		{
			$filter = $(this);
			
			var $filter_links = $filter.find('ul a');
			
			$filter_links.click(function()
			{
				var $this = $(this);

				$this.parent('li').siblings().removeClass('sel').end().addClass('sel');

				var cat_name = $this.attr('href');

				cat_name = cat_name.substring(1);

				var $list_items = $filter.parent().find('.listing li');

				$list_items.show();

				if (cat_name != 'all')
				{
					$list_items.not('[class~=' + cat_name + ']').hide();
				}

				return false;
			});
		});
	}
}

var ProdSample =
{
	init:function()
	{
		this.init_additional_text_toggle();
		this.init_news_entry_resize();
	},
	
	init_additional_text_toggle:function()
	{
		if (! $('#prod-sample').size())
		{
			return false;
		}
		
		var $additional_text = $('div.additional-text');
		var $toggle_link = $('#prod-sample p.toggle-additional a');
		
		if (! $additional_text.size() || ! $toggle_link.size())
		{
			return false;
		}
				
		$toggle_link.toggle(function()
		{
			$additional_text.fadeIn('fast');
			return false;
		},
		function()
		{
			$additional_text.fadeOut('fast');
			return false;
		});
	},
	
	init_news_entry_resize:function()
	{
		var $news_entry = $('#prod-sample div.entries div.first div.excerpt');
		
		if (! $news_entry.size())
		{
			return false;
		}
		
		var news_entry_height = parseInt($news_entry.css('height'));
		
		if (news_entry_height > 150)
		{
			$news_entry.addClass('shrunk');
			
			$news_entry.after('<p class="show-more"><a href="#">Read the entire text</a></p>');
			
			$('div.entries > div').equalizeCols();
			
			$news_entry.parent('div').find('p.show-more a').toggle(function()
			{
				$news_entry.removeClass('shrunk');
				$('div.entries > div').equalizeCols();
				return false;
			},
			function()
			{
				$news_entry.addClass('shrunk');
				$('div.entries > div').equalizeCols();
				return false;
			});
			
			
		}
	}
};

var Newsletter =
{
	init:function()
	{
		var $form = $('#subscribe form');

		$('#subscribe p:first a').click(function()
		{
			$(this).parents('p').eq(0).remove();
			$form.fadeIn('fast').find('input:text').focus();
			return false;
		});
	}
}

var Entries =
{
	init:function()
	{
		if ( ! $('div.entries-list').size())
		{
			return false;
		}
		
		this.init_short_entries();
	},
	
	init_short_entries:function()
	{
		var $items = $('div.item');

		if ($items.size() < 2 && ! $('div.entries-list').hasClass('single'))
		{
			return false;
		}

		$items.each(function()
		{
			var $this = $(this);

			//var $first_p = $this.find('p:first');

			var $elems_to_hide = $this.find('div.body > *:gt(2)'); // Select plain texts paragraphs except the first one

			// Check if we have more than one paragraph
			// If so, hide it and append link for toggling that hidden stuff
			if ($elems_to_hide.size()) 
			{
				$elems_to_hide.hide();

				$this.find('div.body').after('<p class="more"><a href="#">Show more</a></p>');			
			}
		});

		// Add toggling for that link we appended here above

		var $more_links = $items.find('p.more a');

		$more_links.toggle(function()
		{
			$(this).text('Show less').parents('div.item').find('p:hidden').fadeIn('fast');
			return false;
		},
		function()
		{
			$(this).text('Show more').parents('div.item').find('div.body > *:gt(1)').fadeOut('fast');
			return false;
		});
	}
};

var Video =
{
	init:function()
	{
		var $mediaspace = $('#prod-sample #mediaspace');
		
		var $embedded_video = $mediaspace.find('embed,object');
		
		var flash_found = ($embedded_video.size()) ? true : false;
		
		if ( ! $mediaspace.size() || ! flash_found)
		{
			return false;
		}
		
		$('#mediaspace').before('<p class="toggle-size"><a href="#">Switch to larger screen</a></p>');

		var $prod_sample = $('#prod-sample');
		
		var $video_toggle_link = $('p.toggle-size a');
		var video_toggle_link_text = $video_toggle_link.text();

		$('p.toggle-size a').toggle(function()
		{
			$prod_sample.addClass('big-vid');
			$embedded_video.css({'width':720,'height':576});
			$(this).text('Revert to normal screen');
			return false;
		},
		function()
		{
			$prod_sample.removeClass('big-vid');
			$embedded_video.css({'width':360,'height':288});
			$(this).text(video_toggle_link_text);
			return false;
		});
	}
};

var Map =
{
	init:function()
	{
		if (GBrowserIsCompatible())
		{
			var map = new GMap2(document.getElementById("map"));
			
			map.setMapType(G_PHYSICAL_MAP);
			
			map.addControl(new GSmallZoomControl3D());
			
			map.setCenter(new GLatLng(51.944264879028765, 40.78125), 3);
			
			// Create our "tiny" marker icon
			var newIcon = new GIcon(G_DEFAULT_ICON);
			newIcon.image = "img/map-pin-web.png";
			
			// Set up our GMarkerOptions object
			markerOptions = { icon:newIcon };
			
			// GEvent.addListener(map, "moveend", function()
			// {
			// 	var center = mapgetElementsByTagName('')getCenter();
			// 	alert(center.toString())
			// });
			
			var markers = new Array();
			
			var bounds = new google.maps.LatLngBounds(); // obj for storing bounds
			
			for ( var i in partners )
			{
				var c_split = partners[i][0].split(',');
				
				var longitude = c_split[0];
				var latitude = c_split[1];
				
				var marker_text = partners[i][1];
				
				var point = new GLatLng(longitude,latitude);

				map.addOverlay(Map.create_marker(point,marker_text,markerOptions));
				
				var latlng = new google.maps.LatLng(longitude,latitude);

				bounds.extend(latlng); // extend bounds with coords
			}
			
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
			
		}
	},
	
	create_marker:function(point,marker_text,markerOptions)
	{
		var marker = new GMarker(point,markerOptions);
		
		GEvent.addListener(marker, "click", function()
		{
			marker.openInfoWindowHtml(marker_text);
		});
		
		return marker;
	}
};

var NavDropDowns =
{			
	init_load_product_samples:function()
	{
		var $drop_down = $('div.ps-dropdown');
		
		var $links = $drop_down.find('ul.cat-nav a');
		
		// clicks for category links
		
		$links.click(function()
		{
			var $this = $(this);
			
			var category = $this.parent('li').attr('class');
			
			$this.parent('li').addClass('sel').end().siblings().removeClass('sel'); // Add/remove sel class for links
			
			
			var drop_down_height = $drop_down.height(); // Get the height of the container

			// Add height to dropdown, we want dont want it to collapse when the list has faded out.
			// Then add a loading class to display the ajax indicator. Finally fade out the list.
			// When this is done, get the new list based on the above url. Then fade In, remove loading class, etc..

			$drop_down.height(drop_down_height).addClass('loading').find('div.thumbs ul').fadeOut(0,function()
			{
				if (category == 'all')
				{
					$drop_down.find('div.thumbs ul li').fadeIn('fast',function()
					{
						$drop_down.height('').removeClass('loading').find('div.thumbs ul').hide().show();
					});
				}
				else
				{
					$drop_down.find('div.thumbs ul li').hide().filter('li[class~="' + category + '"]').fadeIn('fast',function()
					{
						$drop_down.height('').removeClass('loading').find('div.thumbs ul').hide().show();
					});
				}
				
			});
			
			return false;
		});
		
		var $list_items = $drop_down.find('div.thumbs ul li');
		
		$links.hover(function()
		{			
			var $this = $(this);
 
			var cat_name = $this.parent('li').attr('class');
			
			var cat_name_split = cat_name.split(' ');
			
			cat_name = cat_name_split[0];
			
			$list_items.removeClass('highlight');			
			
			if (cat_name == 'all')
			{
				$list_items.addClass('highlight');
			}
			else
			{
				$list_items.filter('[class~=' + cat_name + ']').addClass('highlight');
			}
			
			return false;
		},
		function()
		{
			$list_items.removeClass('highlight');
			
			return false;
		})
	}
};


jQuery.fn.contactcard = function(pat)
{
	function innerHighlight(node, pat)
	{
		var skip = 0;
		if (node.nodeType == 3)
		{
   			var pos = node.data.toUpperCase().indexOf(pat);
   			if (pos >= 0)
			{
    			var spannode = document.createElement('span');
    			spannode.className = 'contactcard';
				spannode.href = '#';
    			var middlebit = node.splitText(pos);
    			var endbit = middlebit.splitText(pat.length);
    			var middleclone = middlebit.cloneNode(true);
    			spannode.appendChild(middleclone);
    			middlebit.parentNode.replaceChild(spannode, middlebit);
    			skip = 1;
   			}
  		}
  		else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName))
		{
   			for (var i = 0; i < node.childNodes.length; ++i)
			{
    			i += innerHighlight(node.childNodes[i], pat);
   			}
  		}
  		
		return skip;
 	}
	
 	return this.each(function()
	{
  		innerHighlight(this, pat.toUpperCase());
 	});
};
