/*
	Vodafone JS
	========================================
	Version:	0.2
	Date:		01/12/09
	Website:	http://musicunlimited.vodafone.co.nz
	Author:		Aim Proximity {Gandalf, Rav4, Cam, Robbet}
*/

var $j=jQuery.noConflict();

var jsVodafone = window.jsVodafone || {};

var rootURL = "themes/musicunlimited/images/";

var ytModuleHeight = 2;
var prevCarHeight;
var tweetsFirst = true;

var currentPage = "/";
var slideNumber;
var YTnumSlidedTo = 1;

var globalVideoCount = 0;

var BlogHpActive = 0;
var BlogHpMax = 4;

/*	Makes the init run at page load
============================================*/
$j(window).load(function() {
	jsVodafone.initialize();

	if (document.getElementById("Form_ReplyForm_Attachment")) {
		document.getElementById("Form_ReplyForm_Attachment").onchange = function() {
			document.getElementById("FileReference").value = this.value;
		};
	}
	
	if (document.getElementById("Form_ReplyForm_Content")) {
		document.getElementById("Form_ReplyForm_Content").onkeyup = function() {
			if (this.value.length > 1000) {
				this.value = this.value.substring(0, limitNum);
			} else {
				document.getElementById("FormWordCount").innerHTML = 1000 - this.value.length + " Characters Left";
			}
		};
	}
	
	if (document.getElementById("Form_EditPostForm_Attachment")) {
		document.getElementById("Form_EditPostForm_Attachment").onchange = function() {
			document.getElementById("FileReference").value = this.value;
		};
	}
	
	if (document.getElementById("Form_EditPostForm_Content")) {
		document.getElementById("Form_EditPostForm_Content").onkeyup = function() {
			if (this.value.length > 1000) {
				this.value = this.value.substring(0, limitNum);
			} else {
				document.getElementById("FormWordCount").innerHTML = 1000 - this.value.length + " Characters Left";
			}
		};
		if (document.getElementById("Form_EditPostForm_Content").value.length > 0) {
			document.getElementById("FormWordCount").innerHTML = 1000 - document.getElementById("Form_EditPostForm_Content").value.length + " Characters Left";
		}
	}
	
});

// Document Ready
$j(function(){
	jsVodafone.setCurrentPage();
	jsVodafone.docReady();
});


/*$j(document).ready(function() {
	//alert("ggg")		
	jsVodafone.docReady();
});*/

// <BUNCH OF RANDOM FUNCTIONS>

var inPanel   = false;
var inProfile = 1;

function findPosX(obj) {
	var curleft = 0;
	if(obj.offsetParent)
		while(1) 
	{
		curleft += obj.offsetLeft;
		if(!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
		else if(obj.x)
		curleft += obj.x;
		
	return curleft;
}

function showShare() {
	if ($j('#sharePanel').css('display') != 'block') {
		$j('#sharePanel').css('left', findPosX(document.getElementById('menuShare')) + 12 + 'px');
		if (inProfile == -1) {
			$j('#sharePanel').css('top', '449px');
		} else {
			$j('#sharePanel').css('top', '118px');
		}
		$j('#sharePanel').css('display', 'block');
	} else {
		$j('#sharePanel').css('display', 'none');
	}
	
	return false;
}

function clearSearchField(obj) {
	if (obj.value == "Search The Forum") {
		obj.value = '';
	} else if (obj.value == '') {
		obj.value = "Search The Forum";
	}
}

function submitForm() {
	document.getElementById("ForumSearchForm").submit();
}

function hlThis(object) { object.className = "rowHL"; }
function unhlThis(object, tothis) { object.className = tothis; }

function memberMenu(obj) {
	
	$j(".member-menu ul li").each(
		function() {
			$j(this).removeClass('active');
		}
	);

	$j(obj).parent().addClass('active');
	
	$j(".member-menu .member-content").each(
		function() {
			$j(this).css("display", "none");
		}
	);
	
	if ($j(obj).parent().attr('id') == 'liDetails') $j("#info-main").css("display", "block");
	if ($j(obj).parent().attr('id') == 'liAvatar') $j("#info-avatar").css("display", "block");
	if ($j(obj).parent().attr('id') == 'liSignature') $j("#info-signature").css("display", "block");
	if ($j(obj).parent().attr('id') == 'liPreferences') $j("#info-preferences").css("display", "block");
}

function updateProfile() {
	document.getElementById('Form_EditProfileForm').submit();	
}
function setProfile() {
	if ($j('input[id=tnc]').attr('checked')) {
		document.getElementById('Form_SaveProfileForm').submit();
	} else {
		alert("Please agree to the Terms & Conditions before submitting your profile details.");
	}
}

// </BUNCH OF RANDOM FUNCTIONS>

jsVodafone.initialize = function() {
	jsVodafone.Common().randomBackground();
	jsVodafone.Common().inputValueRemove();
	jsVodafone.Common().checkBox();
	// Below rips out all the PNG images in IE6, and uses the filter in an IE6 only stylesheet
	if ($j.browser.msie && $j.browser.version <= 6) {
		jsVodafone.Common().fixIE6();
	}
	
	if ($j('.dropdown')) jsVodafone.Common().galleryDropDown();
	
	switch (currentPage) {
		case "/":
		case "/home-page":
			jsVodafone.initializeHomepage();
		break;
		case "/new-page":
			jsVodafone.initializeHomepage();
		break;
	}
	
}

jsVodafone.initializeHomepage = function() {
	// Vote Module
	jsVodafone.Common().voteModule();
	jsVodafone.Common().checkBox();
	
	jsVodafone.Common().blogModule();
	
	// Video Module
	jsVodafone.Common().videoNextPrev();
	
	// Gallery Module
	jsVodafone.Common().thisGallery();
	jsVodafone.Common().galleryDropDown();
	jsVodafone.Common().gallerySelect();
}

jsVodafone.docReady = function() {
	
	switch (currentPage) {
		case "/":
		case "/home-page":
			jsVodafone.docReadyHomepage();
		break;
	}
	jsVodafone.Common().initPollForms();
	jsVodafone.Common().initVideos();
	jsVodafone.Common().loadAjax("referfriend", "vfmusicfgf/", "fgf");
	
	$j(".updateprofile").each(
		function(intIndex) {
			$j(this).bind ("click", function() {
				$j('#sharePanel').css('display', 'none');
				$j("#profile-panel").slideToggle("slow");
				$j(".logintext").toggle(); $j(".details").toggle(); $j("#topbar").toggleClass('off');
				inProfile *= -1;
			}
			);
		}
	);

	$j("input:checkbox").each( function() {
		(this.checked) ? $j("#fake"+this.id).addClass('fakechecked') : $j("#fake"+this.id).removeClass('fakechecked');
	});
	
	$j(".fakecheck").each(
		function() {
			$j(this).bind ("click", function() {
				($j(this).hasClass('fakechecked')) ? $j(this).removeClass('fakechecked') : $j(this).addClass('fakechecked');
				$j(this.hash).trigger("click");
				return false;
			}
			);
		}
	);

}

jsVodafone.docReadyHomepage = function() {
//	jsVodafone.Common().getYouTube(urlsegment);
//	jsVodafone.Common().showRandomVid();
	jsVodafone.Common().getTwitterStreams();
	jsVodafone.Common().getFlickrIntGallery();
//	jsVodafone.Common().embedYTFlash();
}

jsVodafone.setCurrentPage = function() {
	
	var getPath = "" + top.location.href.split(".nz")[1];
	var start=getPath.indexOf("/");
	var end=getPath.indexOf("/",start)-1;
	var endQmark=getPath.indexOf("?",start)-1;
	if (endQmark<0) endQmark=getPath.length;
	if (end<0) end=getPath.length;
	//alert(end);
	
	if (endQmark < end) {
		var result=getPath.substring(start,endQmark);
		var result='';
		for(var i=start;i<=endQmark;i++) {
			var c=getPath.charAt(i);
			result=result+(c==' + '?' ':c);
		}
	} else {
		var result=getPath.substring(start,end);
		var result='';
		for(var i=start;i<=end;i++) {
			var c=getPath.charAt(i);
			result=result+(c==' + '?' ':c);
		}
	}
	
	currentPage = unescape(result);
	
}

/*	Common functions, that can be re-called at any point.
============================================*/
jsVodafone.Common = function() {
/*
	var embedYTFlash = function() {
		var so = new SWFObject("themes/musicunlimited/flash/YouTubePlayer.swf", "MainYTPlayer", "450", "292", "9", "#ffffff");
		so.addParam("wmode", "transparent");
		so.addParam("allowScriptAccess", "always");
		so.write("YTPlayer");
	}
*/
	// Random background chooser
	var randomBackground = function() {
		bgImageTotal=8;
		randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
		imgPath = (rootURL+'0'+randomNumber+'.jpg');
		$j("body").css({background: "#1E2A2D url('"+imgPath+"') center top no-repeat"});
	}

	// Make all the modules even height
	var initColHeight = function() {
		$j(".row").each(function(){
			$j(this).find(".inner").css({height: "auto"});
			var rowHeight = $j(this).height();
//			alert($j(this).attr("id") + " | " + $j(this).parent().attr("class"));
			
			//alert($j(this).find("div").hasClass("blog"))
			
			if($j(this).find("div").hasClass("blog")){
				$j(this).find(".inner").css({height: (rowHeight + 40) + "px"})
			} else {
				$j(this).find(".inner").css({height: rowHeight + "px"});
			}
			//}
			
//			var dickens = $j(this).find(".inner div");
//if (dickens.length > 3) { if ($j(dickens[3]).attr('id').indexOf("AboutVid") > -1) alert($j(dickens[3]).attr('id') + " | " + $j(dickens[3]).height()); }
//			var bollocks  = $j(this).find("div.inner");
//			var bigNumber = 0;

//			for (i=0;i<bollocks.length;i++) {
//				$j(bollocks[i]).css({height: "auto"});
//				var rowHeight = $j(bollocks[i]).height();
//
//				if (rowHeight > bigNumber) bigNumber = rowHeight;
//			}
			
//			for (i=0;i<bollocks.length;i++) {
//				$j(bollocks[i]).css({height: bigNumber + "px"});
//			}
			
//			alert(bigNumber);
			
//				alert($j(this).parent().attr("className"));
		});
		
		var lockout = $j.find(".jScrollPaneDrag");

		if (tweetsFirst) {
			tweetsFirst = false;
			setTimeout(feedsHeight, 500);
		}
	}
	
	// Make the feed height fill the module
	var feedsHeight = function() {
		var feedHeight 		= $j(".feeds .inner").outerHeight();
		var totalHeight		= 0;
		$j(".feeds .inner").each(function(i) {
			$j(this).children().each(function() {
				if($j(this).attr("class") != 'twitter'){
					totalHeight += $j(this).outerHeight();
				}
			});
		});
//		alert(feedHeight + " | " + totalHeight);
		var heightWeWant = feedHeight - totalHeight;
	
		$j(".border").css({height: heightWeWant - 34 + "px"});
		$j(".twitter").css({height: heightWeWant - 36 + "px"});
		
		// Scroll bar styling plugin
		$j('.twitter').jScrollPane({showArrows:true, scrollbarWidth: 21, arrowSize: 21});
	}
	
	var initPollForms = function() {
		$j(".ShowPoll").each(function() {
			
			var URLID = $j(this).find(":input[name='URLID']").val();
			var updateObj = "output_" + URLID;
			
			$j(this).bind('submit', function() {
				$j(this).ajaxSubmit({
					target: "#" + updateObj,
					beforeSubmit:  showLoading,
					success:  jsVodafone.Common().updateAfterAjax("poll", URLID)
				});
				return false;
			});
						
			$j("#preview_" + URLID).click(function() {
				$j("#previewOutput_" + URLID).show();
				$j("#" + updateObj).hide();
				initColHeight();
				return false;
			});
			
			$j("#backTo_" + URLID).click(function() {
				$j("#previewOutput_" + URLID).hide();
				$j("#" + updateObj).show();
				initColHeight();
				return false;
			});
			
			function showLoading(formData, jqForm, options) {
			   $j(updateObj).html("<center><img src='"+rootURL+"/loadingAnimation.gif' /></center>");
			}
			
		});
	}
	
	// Login
	var inputValueRemove = function() {
		$j("#login input").click(function() {
			$j(this).val("");
		});
	}
	
	// Form Checkbox
	var checkBox = function() {
		$j(".checkbox").toggle(function() {
			$j(this).addClass("active");
			$j(this).find("input").attr("checked", "checked");
			},function(){
			$j(this).removeClass("active");
			$j(this).find("input").attr("checked", "");
		});
	}

	// Form Checkbox
	var checkBox = function() {
		$j(".checkbox").toggle(function() {
			$j(this).addClass("active");
			$j(this).find("input").attr("checked", "checked");
			},function(){
			$j(this).removeClass("active");
			$j(this).find("input").attr("checked", "");
		});
	}

	// Vote Module
	var voteModule = function() {
		$j("#PollAnswer li label").click(function() {
			$j(this).parent().find("input").attr("checked", "checked");
			$j("#PollAnswer li").each(function() {
				$j(this).removeClass("selected");
			});
			$j(this).parent().addClass("selected");
		});
		
		var name;
		$j("#PollAnswer li a").click(function() {
			var name 	= $j(this).parent().parent().find("span").attr("rel"); //$j(this).parent().parent().parent().find("label").text();
			var text 	= $j(this).attr("title");
			var id	= name.replace(" ", "").replace(" ", "").replace("'", '').toLowerCase();
			
			$j(this).addClass("active");
			$j(this).after('<div class="popup"><h4>' +  name + '</h4><p>' + text + '</p><a id="' + id + '" href="#' + id +'">View submitted photos &raquo;</a></div>');
			$j(".popup").stop().animate({height: "show"}, 500);
			$j(".popup a#" + id).click(function() {
				scrollWinTop();
				galleryVoteSelect(id);
				return false;
			});
			return false;
		});

		$j("#PollAnswer li").mouseleave(function() {
			$j(".popup").stop().animate({height: "hide"}, 500);
			$j("a").removeClass("active");
			$j(".popup").remove();
		});
	}
	
	var blogModule = function() {
		$j(".blogSummaryHP").each(function(i) {
			$j(this).attr("id", "blogSummaryHP" + i);
			BlogHpMax = i;
		});
		
		$j("#BlogNavHP .prev").click(function() {
			$j("#blogSummaryHP" + BlogHpActive).hide();
			BlogHpActive--;
			if(BlogHpActive < 0){
				BlogHpActive = BlogHpMax;
			}
			
			$j("#blogSummaryHP" + BlogHpActive).show();
			initColHeight();
			return false;
		});
		
		$j("#BlogNavHP .next").click(function() {
			$j("#blogSummaryHP" + BlogHpActive).hide();
			BlogHpActive++;
			if(BlogHpActive > BlogHpMax){
				BlogHpActive = 0;
			}
			$j("#blogSummaryHP" + BlogHpActive).show();
			initColHeight();
			return false;
		});
		
		//BlogHpActive
	}
	
	// Video Module
	var videoNextPrev = function() {
		var listLength 		= $j(".youtube ul li").length / $j(".youtube").length;
		var listWidth 		= $j(".youtube ul li:first").outerWidth(true);
		var totalWidth 		= listLength * listWidth;
		var listMove		= listWidth * 3;
		$j(".youtube ul").css({width: totalWidth + "px"});
		
		
		$j(".video").each(function() {
				var URLID = $j(this).find(":input[name='URLID']").val();
				if(listLength <= 3) {
					$j(".youtube:[rel='"+URLID+"'] .galleryNext a").hide();
				}
		});
				
		// Click Next
		$j(".youtube .galleryNext a").hover(function() {
			$j(this).not(".selected").parent().parent().parent().find("ul").animate({'marginLeft': '-30px'}, 500);
			 },function(){
			$j(this).parent().parent().parent().find("ul").animate({'marginLeft': '0'}, 500);
		});
		$j(".youtube .galleryNext a").click(function() {
			var temp = $j(this).parent().parent().parent();

			var nextPosition	= $j(".youtube:[rel='"+temp.attr("rel")+"'] ul").css("left");
			var nextValue		= parseFloat(nextPosition);
			var moveNext 		= nextValue - listMove;

			$j(".youtube:[rel='"+temp.attr("rel")+"'] ul").animate({left: moveNext+"px"}, 1500);
			hideNextPrev(moveNext, totalWidth, listMove, temp.attr("rel"));
			return false;
		});
		
		// Click Previous
		$j(".youtube .galleryPrevious a").hover(function() {
			$j(this).not(".selected").parent().parent().parent().find("ul").animate({'marginLeft': '30px'}, 500);
			 },function(){
			$j(this).parent().parent().parent().find("ul").animate({'marginLeft': '0'}, 500);
		});
		$j(".youtube .galleryPrevious a").click(function() {
			var temp = $j(this).parent().parent().parent();
														 
			var prevPosition	= $j(".youtube:[rel='"+temp.attr("rel")+"'] ul").css("left");
			var prevValue		= parseFloat(prevPosition);
			var movePrev 		= prevValue + listMove;
			
			$j(".youtube:[rel='"+temp.attr("rel")+"'] ul").animate({left: movePrev+"px"}, 1500);
			hideNextPrev(movePrev, totalWidth, listMove, temp.attr("rel"));
			return false;
		});
	}
	
	//-------------
	var initVideos = function() {
		$j(".video").each(function() {
								   
			var URLID = $j(this).find(":input[name='URLID']").val();
			var temp = $j(this).find(":li[name='vidthumb']");
			
			var so = new SWFObject("themes/musicunlimited/flash/YouTubePlayer.swf", "MainYTPlayer_" + URLID, "450", "292", "9", "#ffffff");
			so.addParam("wmode", "transparent");
			so.addParam("allowScriptAccess", "always");
			so.write("YTPlayer_" + URLID);
			
			jsVodafone.Common().loadAjax("YTGalleryAboutVid_" + URLID, $j("#youtubeCarousel:[rel='"+URLID+"'] li#" + $j(temp[0]).attr("id") + " a").attr("href"), "ytCallBack", URLID);
			
//			$j(this).ajaxSubmit({
//				target: "#" + updateObj,
//				beforeSubmit:  showLoading,
//				success:  jsVodafone.Common().updateAfterAjax("poll", URLID)
//			});
			
			for(i=0;i<temp.length;i++) {
				$j(temp[i]).bind('click', function(event) {
					jsVodafone.Common().loadAjax("YTGalleryAboutVid_" + URLID, $j("#youtubeCarousel:[rel='"+URLID+"'] li#" + $j(this).attr("id") + " a").attr("href"), "ytCallBack", URLID);
					jsVodafone.Common().selectYTVid($j(this).attr("rel"), URLID);

					return false;
				});
			}
			
			function showLoading(formData, jqForm, options) {
			   $j(updateObj).html("<center><img src='"+rootURL+"/loadingAnimation.gif' /></center>");
			}
			
		});
	}
	//-------------
	
	// Slides Pagination to the right video
	var videoSlide = function(n) {
		
		var listLength 		= $j(".youtube ul li").length;
		var listWidth 		= $j(".youtube ul li:first").outerWidth(true);
		var visWidth		= $j(".youtube .scroll").outerWidth(true);
		var numShowing		=  Math.round(visWidth / listWidth);
		
		var totalWidth 		= listLength * listWidth;
		var num = Math.ceil((listWidth * numShowing));
		var moveIt = num * (Math.ceil(n / numShowing) -1);
		
		$j(".youtube ul").animate({left: "-"+moveIt+"px"}, 1500);
		
		hideNextPrev(-moveIt, totalWidth, num, "none");
	}
	
	var hideNextPrev = function(move, totalWidth, listMove, URLID) {
		
		var testValue = totalWidth - listMove;
		
		if(-testValue >= move) {
			$j(".youtube:[rel='"+URLID+"'] .galleryNext a").hide();
		} else {
			$j(".youtube:[rel='"+URLID+"'] .galleryNext a").show();
		}
		
		if (move >= 0) {
			$j(".youtube:[rel='"+URLID+"'] .galleryPrevious a").hide();
		}  else {
			$j(".youtube:[rel='"+URLID+"'] .galleryPrevious a").show();
		}
	}
	
	var thisGallery = function() {
		
		$j(".flickr .dropdown ol li").each(function() {
			var whatSelected = $j(this).attr("class");
			if (whatSelected == "selected") {
				whatId = $j(this).children("a").attr("class");
			}
		});
		
	}
	
	var galleryShow = function(id) {
		$j(".flickr .scroll").each(function() {
			var galleryId = $j(this).attr("id");
			if(id == galleryId) {
				$j(this).animate({height: "show"}, 750).addClass("selected");;
			} else {
				$j(this).animate({height: "hide"}, 750).removeClass("selected");
			}
		});
	}
	
	// Next Previous
	/*var galleryNextPrev = function(whatId) {
		// Click Next
		
		
		// Click Previous
		$(".flickr .galleryPrevious a").hover(function() {
			$(this).not(".selected").parent().parent().parent().find("#"+whatId+" ul").animate({'left': '10px'}, 500);
			 },function(){
			$(this).parent().parent().parent().find("#"+whatId+" ul").animate({'left': '0'}, 500);
		});
		$(".flickr .galleryPrevious a").click(function() {
			$("#"+whatId+" ul").stop().animate({left: "460px"}, 1500).addClass("remove");
			gallerySlide(whatId);
			return false;
		});
	}*/
	
	var flickrGalleryInit = function () {
		jsVodafone.Common().galleryNext();
		jsVodafone.Common().galleryPrevious();
		jsVodafone.Common().flickrCreatePagination();
	}
	
	var flickrGalleryPagination = function () {
//		alert($j("#flickrPageUrl").attr("rel"));
//		alert("WHAT NOW " + $j("#flickrPageUrl").attr("rel") + "/getFlickrPagination/?ThePage=" + $j("#flickrPage").attr("rel") + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"));
		jsVodafone.Common().loadAjax("ajaxFlickrPagination", $j("#flickrPageUrl").attr("rel") + "/getFlickrPagination/?ThePage=" + $j("#flickrPage").attr("rel") + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"), "flickrPagination");
	}
	
	var flickrCreatePagination = function () {
		//flickrPagNums
//		alert($j.find(".flickrPagNums").length);
		$j(".flickrPagNums").each(function(){
			//var id = $j(this).attr("id");
			var theHref = $j(this).attr("href");

			if (theHref.indexOf("//") > -1) {
				theHref = theHref.split("/");
				theHref = theHref[3] + '/' + theHref[4] + '/' + theHref[5];
			}

			$j(this).click(function() {
				clearflickrPagination();
				jsVodafone.Common().loadAjax("ajaxFlickrContent", theHref + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"), "flickrGallery");
				return false;
			});
			
		});
	}
	
	var galleryNext = function() {
		
		$j("#galleryNext").click(function() {
			$j(".flickrGallerySlide").stop().animate({left: "-460px"}, 1500).addClass("remove");
			clearflickrPagination();
			
			var theHref = $j(this).attr("href");
			if (theHref.indexOf("//") > -1) {
				theHref = theHref.split("/");
				theHref = theHref[3] + '/' + theHref[4] + '/' + theHref[5];
			}
			// alert(theHref + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"));
			jsVodafone.Common().loadAjax("ajaxFlickrContent", theHref + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"), "flickrGallery");
			return false;
		});
		
		$j("#galleryNext").hover(function() {					  
			$j(".flickrGallerySlide").animate({'marginLeft': '-10px'}, 500);
			//$j(this).not(".selected").parent().parent().parent().find("#"+whatId+" ul").animate({'marginLeft': '-10px'}, 500);
			 },function(){
			$j(".flickrGallerySlide").animate({'marginLeft': '0'}, 500);
			//$j(this).parent().parent().parent().find("#"+whatId+" ul").animate({'marginLeft': '0'}, 500);
		});
	}
	
	var galleryPrevious = function() {
		
		$j("#galleryPrevious").click(function() {
			$j(".flickrGallerySlide").stop().animate({left: "460px"}, 1500).addClass("remove");
			clearflickrPagination();
			
			var theHref = $j(this).attr("href");
			if (theHref.indexOf("//") > -1) {
				theHref = theHref.split("/");
				theHref = theHref[3] + '/' + theHref[4] + '/' + theHref[5];
			}
			// alert(theHref + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"));
			jsVodafone.Common().loadAjax("ajaxFlickrContent", theHref + "&SearchTag=" + $j("#flickrTag").attr("rel") + "&URLID=" + $j("#flickrPageUrl").attr("rel"), "flickrGallery");
			return false;
		});
		
		$j("#galleryPrevious").hover(function() {					  
			$j(".flickrGallerySlide").animate({'left': '10px'}, 500);
			 },function(){
			$j(".flickrGallerySlide").animate({'left': '0'}, 500);
		});		
	}
	
	var clearflickrPagination = function () {
		$j("#ajaxFlickrPagination").html("");
	}
	
	var getFlickrIntGallery = function () {
		
		thisGallery();
		jsVodafone.Common().loadAjax("ajaxFlickrContent", $j(".browse .dropdown ol .selected a").attr("href"), "flickrGallery");
		return false;
		
	}
	
	/*var gallerySlide = function(whatId) {		
		$("#"+whatId).append('<ul><li>AJAX</li></ul>');
	
		function delay() {
			$("#"+whatId+" ul.remove").remove();
		}
		setTimeout(delay, 1500);
	}*/
	
	// DropDown
	var galleryDropDown = function() {
		$j(".dropdown ol").append('<li class="last"></li>');

		$j(".dropdown ol").hover(function() {
		  $j(this).addClass("active");
		});

		$j(".dropdown ol").mouseleave(function() {
			$j(this).removeClass("active");
			return false;
		});
	}
	
	var delayDropDown = function() {
		$j(".dropdown ol").addClass("active");
	}
	
	// Gallery select
	var gallerySelect = function() {
		$j(".dropdown ol li").click(function() {
			var id = $j(this).children("a").attr("class");
			$j(".browse .dropdown ol li").each(function() {
				$j(this).removeClass("selected");
			});
			$j(this).addClass("selected");
			thisGallery();
			jsVodafone.Common().loadAjax("ajaxFlickrContent", $j(this).children("a").attr("href"), "flickrGallery");
			return false;
		});
	}

	// If seleceted from vote
	var galleryVoteSelect = function(id) {
		$j(".dropdown ol li").each(function() {
			$j(this).removeClass("selected");
			var galleryId  = $j(this).children("a").attr("class");
			if(id == galleryId) {
				$j(this).addClass("selected");
				jsVodafone.Common().loadAjax("ajaxFlickrContent", $j(this).children("a").attr("href"), "flickrGallery");
			}
		});
		thisGallery();
		return false;
	}

	var scrollWinTop = function(){
		$j('html, body').animate({
			scrollTop: $j(".flickr").offset().top}, 1000);
	}
	
	var fixIE6 = function() {
		// IE6 PNG remover
		$j("img").each(function(){
			if ($j(this).attr("src").match(/\.png$/) != null) {
				if ($j(this).hasClass("png")) {
					$j(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + $j(this).attr("src") + "', sizingMethod='crop')");
				}
				$j(this).attr("src", "images/spacer.gif");
			}
		});
		// IE6 Style sheet, to add filtered PNG's
		//$j("head").createAppend('link', {rel: 'stylesheet', href: '../css/ie6.css', type: 'text/css', media: 'screen'});
	}
	
	
	// ==== Robbies ==============================================================
	
	
	var TweetQuery = '';
	var IDArray = new Array();
	
	var getTwitterStreams = function()
	{
//		alert("STREAMS");
//		if(TweetQuery == ''){
//			TweetQuery = query;	
//		}
		
//		var url = TweetQuery;
//		urlCount = 0;

//		$j(".twitter").attr("rel")
		
		$j(".twitter").each(function() {
			
			callTweeter($j(this).attr("rel"));
			
		});
		
//		initColHeight();
//		feedsHeight();
	}
	
	var callTweeter = function(url) {
		$j.getJSON(url, function(data){
          	$j.each(data.results, function(i,item){
				IDArray = new Array();
				var imgsrc = item.profile_image_url;
				var id = item.id;
				//if(idexists(id) == false){
					IDArray.push(id);
					var divTweet = '<div class="tweet" id="tweet'+ id +'">' + '\n';
						divTweet += '<div class="triangle"></div>' + '\n';
						divTweet += '<a href="https://www.twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="View this tweet on Twitter" target="_blank"><img src="'+ imgsrc +'" alt="" /></a>' + '\n';
						divTweet += '<div class="post">' + '\n';
						divTweet += linkify(item.text) + '\n';
						divTweet += '<ul>' + '\n';
						divTweet += '<li class="name">By <a href="http://www.twitter.com/'+ item.from_user +'" target="_blank">'+ item.from_user +'</a></li>' + '\n';
						divTweet += '<li class="posted">Posted <strong>'+relative_time(item.created_at)+'</strong></li>' + '\n';
						divTweet += '</ul>' + '\n';
						divTweet += '</div>' + '\n';
						divTweet += '</div>' + '\n';
					
					$j(".twitter:[rel='"+url+"'] #twitterscrollpane").append(divTweet);
					$j(".twitter:[rel='"+url+"'] #twitterscrollpane #tweet" + id).fadeIn("slow").slideDown("fast");
					
					if(item.from_user == 'vodafonenz'){
						$j(".twitter:[rel='"+url+"'] #twitterscrollpane #tweet" + id).addClass('vodafone');
					}
				/*} else {
					alert("Exists : " + id + ' length ' + IDArray.length);
				}*/
				
          	});
        });
		
		//setTimeout(getTwitterStream, 5000);
	}
	
	var linkify = function(val) {
		return val.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
		return m.link(m);
		});
	};
	
	var relative_time = function(time_value) {		
		var TwitterValues = time_value.split(" ");
		
		//alert("values[1] " + values[1] + "values[2] " + values[2] + "values[3] " + values[3] + "values[4] " + values[4] + "values[5] " + values[5])
		
		var Twitter_parsed_date = new Date(Date.parse(TwitterValues[4] + " " + numberMonth(TwitterValues[2]) + "/" + TwitterValues[1] + "/" + TwitterValues[3]));
		
		//alert(TwitterValues[4])
		
		var dateNow = new Date();
		var dateNow_parsed_date = dateNow.getTime();
		
		//dateNow.toString();
		//var dateNowValues = dateNow.split(" ");
		
		//var dateNow_parsed_date = new Date(Date.parse(dateNow.getDate() + 1 + "/" + dateNow.getMonth() + 1 + "/" + dateNow.getFullYear()));
		
		/*var relative_to = (arguments.length > 1) ? arguments[1] : new Date();*/
		var delta = parseInt((dateNow_parsed_date - Twitter_parsed_date) / 1000);
		delta = delta + (dateNow.getTimezoneOffset() * 60);
		
		//var delta = Math.ceil((dateNow_parsed_date - Twitter_parsed_date) / 1000);
		
		var r;
		if (delta < 60) {
			r = 'a minute ago';
		} else if(delta < 120) {
			r = 'couple of minutes ago';
		} else if(delta < (45*60)) {
			r = (parseInt(delta)).toString() + ' minutes ago';
		} else if(delta < (90*60)) {
			r = 'an hour ago';
		} else if(delta < (24*60*60)) {
			r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
		} else if(delta < (48*60*60)) {
			r = '1 day ago';
		} else {
			r = (parseInt(delta / 86400)) + ' days ago';
		}
		
		return r;
	};
	
	var numberMonth = function(month)
	{
		switch(month) {
			case "Jan":
				return "01";
			break;
			case "Feb":
				return "02";
			break;
			case "Mar":
				return "03";
			break;
			case "Apr":
				return "04";
			break;
			case "May":
				return "05";
			break;
			case "Jun":
				return "06";
			break;
			case "Jul":
				return "07";
			break;
			case "Aug":
				return "08";
			break;
			case "Sep":
				return "09";
			break;
			case "Oct":
				return "10";
			break;
			case "Nov":
				return "11";
			break;
			case "Dec":
				return "12";
			break;
		}
	};
	
	var twitter_callback = function()
	{
		return true;
	};
	
	var idexists = function(thisID)
	{
		if(IDArray.length <= 1){ 
			return false;
		} else {
			for(var i = 0; i < IDArray.length; i++){
				if((thisID != IDArray[i])){
					return false;
				} else {
					return true;
				}
			}	
		}
		
	}
	
	
	var getYouTube = function(seg)
	{
		var urlseg = seg;
		//alert(urlseg);
		
		$j("#youtubeCarousel li").each(function(nu){
			var id = $j(this).attr("id");
			var element = this;
			var url = "http://gdata.youtube.com/feeds/videos/" + id + "?alt=json-in-script&callback=?";
			
			$j.getJSON(url, function(data){
				/*var dID = data.entry.id.$t;
				var genId = dID.substr(38);
				var genImg = data.entry.media$group.media$thumbnail[0].url;

				$j("#youtubeCarousel li#" + id + " .sumthumb").append('<img src="'+genImg+'" height="72" width="120" alt="" />');
				
				if(data.entry.gd$rating != undefined) {
					$j("#youtubeCarousel li#" + id + " .stars").addClass('star' + Math.round(data.entry.gd$rating.average));
				}
				*/
				$j("#youtubeCarousel li#" + id + " a").click(function(){
					slideNumber = nu + 1;
					var theHref = $j(this).attr("href");
					var theRel = $j(this).attr("rel");
					jsVodafone.Common().loadAjax("YTGalleryAboutVid", theHref, "ytCallBack");
					jsVodafone.Common().selectYTVid(theRel);
					return false;
				});
				/*
				var totalSeconds = data.entry.media$group.yt$duration.seconds;
				var minutes = Math.floor(totalSeconds / 60); 
				var seconds = totalSeconds - (minutes * 60);
				var minStr = minutes.toString();
				var secStr = seconds.toString();
				if(minStr.length == 1){
					minStr = "0" + minStr;
				}
				if(secStr.length == 1){
					secStr = "0" + secStr;
				}
				var finTime = minStr + ":" + secStr;
				
				$j("#youtubeCarousel li#" + id + " .time").append(finTime);*/
			});
		});
		
		$j("#youtubeCarousel li:last").addClass("last");
	}
	
	var showRandomVid = function()
		{
			//alert("showRandomVid");
			var maxNum = $j("#youtubeCarousel li").length;
			//var rndm = 0;
			var rndm = Math.floor(Math.random() * maxNum);
			
			var num = $j("#youtubeCarousel li:eq("+rndm+")").attr("rel");
			//alert(num);
			//var vidID = $j("#youtubeCarousel li:eq("+rndm+")").attr("id");

			//var number = rndm + 2;		
			slideNumber = rndm + 1;
			
			$j("#youtubeCarousel li:eq("+rndm+") a").addClass('selected');
			
			jsVodafone.Common().loadAjax('YTGalleryAboutVid', $j("#youtubeCarousel").attr("rel") + '/updateYTModule/' + num + '', "ytCallBack");
			
			prevCarHeight = $j(".youtube").height() + $j("#YTGalleryAboutVid").height();
			//alert(prevCarHeight);
			return false;
		}
	
	var ytAfterAjax = function()
	{
//		alert("AFTERAJAX");
//		jsVodafone.Common().videoSlide(slideNumber);
		initColHeight();
	}
	
	var selectYTVid = function(toID, URLID) {
		$j("#youtubeCarousel:[rel='"+URLID+"'] li").each(function(){
			$j("#youtubeCarousel:[rel='"+URLID+"'] li a").removeClass('selected');
		});
		$j("#youtubeCarousel:[rel='"+URLID+"'] li:[rel='"+toID+"'] a").addClass('selected');
		
		var vID = $j("#youtubeCarousel:[rel='"+URLID+"'] li:[rel='"+toID+"']").attr('id');
		sendVidIDtoFlash(vID, URLID);
	}
	
	var loadAjax = function(loadIntoElID, page, caller, URLID) {
		var completeURL = jQuery('base').attr('href') + page;
		var imgHtml = "<center><img src='"+rootURL+"/loadingAnimation.gif' /></center>"; //'<img src="mysite/javascript/loading.gif" alt="loading . . ." />';
		jQuery("#" + loadIntoElID).html(imgHtml);
		jQuery("#" + loadIntoElID).load(completeURL, {}, function() {
		  /* another function here that runs after content has been loaded */
		  jsVodafone.Common().updateAfterAjax(caller, URLID);
		});
		return false;
	}
	
	var loadAjaxSilent = function(loadIntoElID, page) {
		var completeURL = jQuery('base').attr('href') + page;
		jQuery("#" + loadIntoElID).load(completeURL, {}, function() {
			//alert(jQuery("#" + loadIntoElID).html());
		});
		
		return false;
	}
	
	var updateAfterAjax = function (caller, URLID){
//		alert(caller + " | " + URLID);
		switch(caller) {
			case "flickrGallery":
				jsVodafone.Common().flickrGalleryPagination();
				setTimeout(runThickbox, 500);
				setTimeout(initColHeight, 500);
			break;
			case "flickrPagination":
				jsVodafone.Common().flickrGalleryInit();
			break;
			case "ytCallBack" :
				//alert(slideNumber);
				ytAfterAjax();
			break;
			case "poll":
				setTimeout(initColHeight, 500);
			break;
		}
	}

	var loadVidID = '';
	
	var sendVidIDtoFlash = function(vidID, URLID) {
		loadVidID = vidID.toString();
//		var vidID = $j("#youtubeCarousel li a.selected").parent().attr("id");
		document.getElementById("MainYTPlayer_" + URLID).sendTextToFlash(loadVidID);
	}

	var getTextFromFlash = function() {
		
		if (globalVideoCount < $j(".youtube").length) {
			
			var temp = $j(".youtube").eq(globalVideoCount);
			
			var vidID = $j("#youtubeCarousel:[rel='"+temp.attr("rel")+"'] li a").parent().attr("id");
			vidID.toString();
			document.getElementById("MainYTPlayer_" + temp.attr("rel")).sendTextToFlash(vidID);
			
			globalVideoCount++;
			
		}
	}
	
	//formSend();
		
	//setTimeout(getTwitterStream, 1000);

	return {
		randomBackground : randomBackground,
		initColHeight : initColHeight,
		feedsHeight : feedsHeight,
		initPollForms : initPollForms,
		initVideos : initVideos,
		inputValueRemove : inputValueRemove,
		videoSlide : videoSlide,
//		embedYTFlash : embedYTFlash,
		
		checkBox : checkBox,
		
		voteModule : voteModule,
		
		blogModule : blogModule,
		
		thisGallery : thisGallery,
		galleryDropDown : galleryDropDown,
		gallerySelect : gallerySelect,
		galleryNext : galleryNext,
		galleryPrevious : galleryPrevious,
		flickrGalleryInit : flickrGalleryInit,
		flickrGalleryPagination : flickrGalleryPagination,
		flickrCreatePagination : flickrCreatePagination,
		getFlickrIntGallery : getFlickrIntGallery,
		
		videoNextPrev : videoNextPrev,
		getYouTube : getYouTube,
		showRandomVid : showRandomVid,
		selectYTVid : selectYTVid,
		
		getTwitterStreams : getTwitterStreams,
		sendVidIDtoFlash : sendVidIDtoFlash,
		getTextFromFlash : getTextFromFlash,

		loadAjax : loadAjax,
		loadAjaxSilent : loadAjaxSilent,
		updateAfterAjax : updateAfterAjax,
		
		fixIE6 : fixIE6
		
	}
}

