var address = new Array();
var lats = new Array();
var longs = new Array();
var imglocs = new Array();
var storenames = new Array();

var baseIcon;

var randSpeeds = new Array();

$(document).ready(function(){
	//initialize();
	
	for(var i = 0; i < 3; i++)
	{
		var seconds = Math.floor(Math.random() * 10);
	
		randSpeeds[i] = (Math.round(Math.random() * 1000) * seconds) + Math.round((1000 + (Math.random() * 500)));
	}
	
	randSpeeds[2] += randSpeeds[1];
	
	//home page slideshow
	$('#scrollA').cycle({
		fx:  'fade',
		delay: randSpeeds[0]
	});
	$('#scrollB').cycle({
   		fx: 'fade',
		delay: randSpeeds[1]
	});
	$('#scrollC').cycle({
		fx:  'fade',
		delay: randSpeeds[2]
	});
	$('#scrollD').cycle('pause');
	
	//ultrasheen and gentletreatment slideshow
	$('#USjScrollL').cycle({
		fx:  'fade',
		timeout: 6000,
		delay: 2000
	});
	
	$('#USjScrollM').cycle({
		fx:  'fade',
		timeout: 6000,
		delay: 0
	});
	
	$('#USjScrollR').cycle({
		fx:  'fade',
		timeout: 6000,
		delay: 4000
	});
		
	//small ad rotation
	$('.surrounder').cycle({
		fx:  'fade',
		timeout: 4000
	});
		
	//small ad rotation
	$('.surrounder2').cycle({
		fx:  'fade',
		timeout: 4000
	});
	
	//vlog comment form
	$('#commAddForm').submit(function()
	{
		addComment();
					
		return false;
	});
	    
    firstItem = null;//the category for the selected link
    //set properties for IE or everything else
    if(navigator.appName == 'Microsoft Internet Explorer') {
		linkMarginLeft = '-12px';
		linkWidth = '180px';
		catFloat = 'left';
		catPosition = 'relative';
		bottomMargin = '3px';
		linkHeight = 10;
		lastChildBottomMargin = '10px';
		lastCatBottomMargin = '0px';
	} else {
		linkMarginLeft = '-15px';
		linkWidth = '199px';
		catFloat = 'inherit';
		catPosition = 'relative';
		bottomMargin = '10px';
		linkHeight = 0;
		lastChildBottomMargin = '14px';
		lastCatBottomMargin = '4px';
	}
    
    //show glow when you mouseover a navigation link
    $('#mainNav li dl dt').hover(
    	function() {
    		//if its the last link in a category
    		if($(this).is(':last-child'))
    		{	
    			$(this).parent().parent().css({'margin': '0px 0 '+ lastChildBottomMargin +' 0px'});
    		}
    		//if it's the last link in the last category, to keep the bottom from jumping up on hover
    		if($(this).parent().parent().is(':last-child') && $(this).is(':last-child'))
    		{
    			$(this).css({'padding-bottom': lastCatBottomMargin});
    		}
    	
      		string = $(this).text();
      		filename = string.replace(/([^0-9a-z-A-Z])/g,'');
      		
      		$(this).css({
      			'display':'block',  
      			'margin': '-4px 0 4px ' + linkMarginLeft,
      			'width':linkWidth, 
      			'background':'url("http://jp-scdn.flwint.net/images/mainNav' + filename + '.png") transparent no-repeat 0 0', 
      			'text-indent':'-9009px'
      		});
						
		//fixes margin on the first item of the selected category in IE
		if($(this).text().slice(0, 4) == ($(firstItem)).text().slice(0,4) && navigator.appName == 'Microsoft Internet Explorer')
    		{
    			$(this).css({'margin': '-8px 0 4px ' + linkMarginLeft});
    		}
		
      		$(this).bind('click', function(){
      			var href = $(this).children().attr('href');
      			
      			window.location = href;
      		});
      	},
      	function() {
    		if($(this).is(':last-child'))
    		{
    			$(this).parent().parent().css({'margin': '5px 0 10px 0'});
    		}
    		
    		if($(this).parent().parent().is(':last-child') && $(this).is(':last-child'))
    		{
    			$(this).css({'padding-bottom': '0px'});
    		}
    		
      		$(this).css({
      			'margin': '0px 0 0px 0',	
      			'display':'block',  
      			'width':'auto', 
      			'background':'',
      			'text-indent':'0'
      		});
      	}
     ); 
     	
	//highlight the navigation link for the current page
	//if the pathname isn't empty
	if(location.pathname == '/index.php' || location.pathname == '/') 
	{
		highlightCategory($("#mainNav li:eq(0) a"));
	} 
	else if(location.pathname == '/store.php') 
	{
		//highlightCategory($("#mainNav #storeLoc a"));
	} 
	else 
	{
		$("#mainNav li dt").find("a[href='"+location.pathname.substring(1)+"']").each(function(){
			string = $(this).text();
	      	filename = string.replace(/([^0-9a-z-A-Z])/g,'');
	      	
	      	$(this).parent().children().each(function(){
	      		//$(this).css({'font-weight':'bold'});
	      	})
	      	
	      	$(this).css({
	      		'display':'block', 
	      		'margin':'-4px 0 0 ' + linkMarginLeft, 
	      		'height':'27px', 
	      		'width':linkWidth, 
	      		'background':'url("http://jp-scdn.flwint.net/images/mainNav' + filename + '.png") transparent no-repeat 0 0', 
	      		'text-indent':'-9009px'
	      	});
	      	
	      	//remove hover event from current link
	      	$(this).parent().unbind();
	      	
	      	highlightCategory($(this).parent().parent().parent().find("span").get(0));
	      	
		//set the first Item in the selected category, so that it can fix the hover margin
	      	firstItem = $(this).parent().parent().parent().find("a").get(0);
		});
		
	}
	
	function highlightCategory(cat) {
		//highlight the category for the current page
      	category = cat;
      	if($(category).height() > 30) 
      	{
      		linkName = 'TwoLiner';
      		linkHeight += 50;
      		topPadding = '8';
      	} 
      	else 
      	{
      		linkName = 'OneLiner';
      		linkHeight += 46;
      		topPadding = '10';
      	}
      	
      	$(category).css({'color':'#fff', 'display':'block', 'float':catFloat, 'position':catPosition, 'margin':'-2px 0 ' + bottomMargin + ' -10px', 'padding':topPadding + 'px 0 17px 10px', /*'height': linkHeight + 'px',*/  'width':'169px', 'background':'url("http://jp-scdn.flwint.net/images/mainNav' + linkName + '.png") transparent no-repeat 0 0'});
	}
	
	//collapsible search results on search page
	$("ul.collapsible").each(
		function()
		{
			iterateList(this);
		}
	);
	
	$('#commTitle').keyup(function(event){
	    limitText(this,30);
	});
	
	$('#commTitle').keydown(function(event){
	    limitText(this,30);
	});
	
	$('#commBody').keyup(function(event){
	    limitText(this,250);
	});
	
	$('#commBody').keydown(function(event){
	    limitText(this,250);
	});
	
	$('.storeSearchBar').keyup(function(event){
	    limitText(this,6);
	});
	
	$('.storeSearchBar').keydown(function(event){
	    limitText(this,6);
	});
	
	$('.searchText').keyup(function(event){
	    limitText(this,30);
	});
	
	$('.searchText').keydown(function(event){
	    limitText(this,30);
	});
	
});

//collapsible search results on search page

function iterateList(node)
{
	var ul, toggleLink;
	// get list items
	$("li",node).each(
		function()
		{
			if(this.parentNode != node) return;
			// if item contains a sub list
			ul = $("ul",this).get(0);
			if(ul)
			{
				$("ul",this).hide();
				toggleLink = document.createElement("a");
				toggleLink.href = "#";
				$(toggleLink).addClass("toggle");
				if(navigator.appName == 'Microsoft Internet Explorer') {
					$(ul.parentNode.childNodes[0]).wrap(toggleLink);
				} else {
					$(ul.parentNode.childNodes[1]).wrap(toggleLink);
				}
				$("a.toggle", ul.parentNode).click(
					function()
					{
						$(">ul",this.parentNode).toggle();
						if($(">ul",this.parentNode).is(':hidden')) {
							$(this).find('img').attr("src", "http://jp-scdn.flwint.net/images/search_arrow.png");
						} else {
							$(this).find('img').attr("src", "http://jp-scdn.flwint.net/images/search_arrow_down.png");
						}
						return false;
					}
				);
				iterateList(ul);
			}
		}
	);
}


//initialize global variable map for gmaps to call
var map;

function initialize(startingPoints)
{
	for(var i in startingPoints)
	{
		var curSplit = startingPoints[i].split('_');
		
		lats[i] = curSplit[0];
		longs[i] = curSplit[1];
		imglocs[i] = curSplit[2];
		storenames[i] = curSplit[3];
		address[i] = curSplit[4];
	}
	
	point = new GMarker(new GLatLng(41.88,-87.62), 13);
	
	map = new GMap2(document.getElementById("mapHolder"));
	
	map.setCenter(new GLatLng(41.8823433,-87.6241936), 13);
	map.setUIToDefault();
		
	for(var i in startingPoints)
	{
		var curPoint = new GLatLng(lats[i], longs[i]);
		map.addOverlay(layMarker(curPoint, address[i], imglocs[i], storenames[i]));
	}
	
	if(startingPoints.length > 0) {
		panMap(lats[0], longs[0]);
	}
}

function panMap(lat, long)
{
	map.panTo(new GLatLng(lat, long));
}

function layMarker(point, address, imgloc, storename)
{
	
	var pushPin = new GIcon(G_DEFAULT_ICON);
	pushPin.image = imgloc;
	pushPin.iconSize = new GSize(36, 72);
	pushPin.iconAnchor = new GPoint(20, 65);
	pushPin.shadow = 'http://jp-scdn.flwint.net/images/pushpins_shadow.png';
	pushPin.shadowSize = new GSize(69, 98);
	pushPin.infoWindowAnchor = new GPoint(10,0);
	pushPin.transparent = 'http://jp-scdn.flwint.net/images/pushpins_transparent.png';
	pushPin.imageMap = [4, 7, 32, 7, 30, 53, 7, 53];
	
	markerOptions = { icon: pushPin };
	
	var curMarker = new GMarker(point, markerOptions);
	
	GEvent.addListener(curMarker, "click", function(){
		curMarker.openInfoWindowHtml("<h3>" + storename + "</h3>" + address);
	});
	
	return curMarker;
}

function addComment()
{
	var commBody = $('#commBody').val();
	var commTitle = $('#commTitle').val();
	var vId = $('#vId').val();
	var pId = $('#pid').val();
	var uId = $('#uid').val();
	//calls js/ajax.php
	$.post('js/ajax.php',
		{method: "addComm", commentTitle: commTitle, commentBody: commBody, vId: vId, pid: pId, uid: uId},
		function(result)
		{			
			if(result === 'toofast')
			{
				alert('You are posting too fast. Please wait before posting on this video again.');
			}
			else if(result !== 'failed')
			{
				//result will return with username & timestamp; split them to display them
				var result = result.split(',');
			
				//comment html before new comment gets added
				var commentHTML = $('#viewAllComm').html();
				//comment count before new comment gets added
				var commcountHTML = $('#commCount').html();
				
				if(commcountHTML.replace(/(Comments|Comment)/, ''))
				{
					//set last comment count + 1 to variable for displaying
					var parsed = commcountHTML.replace(/No/, '') ? 0 : (parseInt(commcountHTML) + 1);
				}
													
				//add new comment to top of list			
				if(commentHTML == '<div class="singComm"><h1>There are no comments for this video!</h1></div>') {
					commentHTML = '';
				}
				commentHTML = '<div class="singComm"><h1>' + commTitle + '</h1><p>' + commBody + '</p><p class="postedby">Posted by ' + result[0] + ' on ' + result[1] + '</div>' + commentHTML;
			
				$('#commCount').html(parsed + " Comments");
				$('#viewAllComm').html(commentHTML);
				$('#commTitle').val('Comment Title');
				$('#commBody').val('');
			}
			else
			{
				alert('failed to add comment');
			}
		}
	);
}
//called by player.swf when it plays a new movie
function getVideoComments(vidId)
{
	$('#vId').val(vidId);
	
	
	$.post('js/ajax.php',
		{vidId: vidId, method: "videoComms"},
		function(comments){
			if(comments != 'failed')
			{
				var singleComments = new Array();
				var indAssocArr = new Array();
				var allComments = new Array();
				
				var commentHTML = "";
								
				//holds all comments after the split
				singleComments = comments.split('+');
				
				for(var i in singleComments)
				{
					//holds single comment with all columns and field values
					indAssocArr = singleComments[i].split('|');
													
					commentHTML += '<div class="singComm"><h1>' + indAssocArr[1] + '</h1><p>' + indAssocArr[2] + '</p><p class="postedby">Posted by ' + indAssocArr[6] + ' on ' + indAssocArr[5] + '</div>';
				}
				
				//change comment count
				$('#commCount').html(singleComments.length + " Comments");
				//change comments
				$('#viewAllComm').html(commentHTML);
			}
			else
			{
				//change comment count
				$('#commCount').html("No Comments");
				//change comments
				$('#viewAllComm').html('<div class="singComm"><h1>There are no comments for this video!</h1></div>');
			}
			$('#commTitle').val('Comment Title');
			$('#commBody').val('');
		}	
	);
}
//used by the vlog to limit the length of comments
//also used by the store locator zip code input
//called by main.js and post.js
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
