var browser;
var browserVersion;
var isIE;
var screenshotGalleryInitialized = false;
var reflectionsInitialized = false;
var bottomLeftContentFilled = false;
var roadmapInitialized = false;

/** Detect the browser and the browser version */
browserDetection = function() {
	browser = navigator.userAgent.toLowerCase();
	browserVersion = parseFloat(browser.substring(browser.indexOf("msie ") + 5));
	isIE = ((browser.indexOf("msie")!=-1) && (browser.indexOf("opera")==-1) && (browser.indexOf("webtv")==1));
}

/** Init screenshot gallery */
initScreenshotGallery = function(data) {
	var markup;
	
	$("#feature_screenshots").html("<ul id=\"screenshot_jcarousel\" class=\"jcarousel-skin-opensuse_hu\"></ul>");
	
	/* convert json string to markup */
	$.each(data, function(i, screenshot) {
		markup = "<li><a href=\"" + screenshot.file_large + "\" title=\"" + screenshot.description + "\"><img src=\""+screenshot.file_small+"\" width=\"200\" height=\"150\"/></a></li>";
		$("#screenshot_jcarousel").append(markup);
	});
	
	/* add gallery slider, reflections and zoombox */
	$("#screenshot_jcarousel").jcarousel({
		visible:4
	});
	$("#feature_screenshots a").fancybox({
		"overlayShow": true
	});
	
	screenshotGalleryInitialized = true;
}

/** Make a reflection on imagse */
reflectImages = function() {
	if (reflectionsInitialized == false) {
		$("#screenshot_jcarousel img").reflect();
		reflectionsInitialized = true;
	}
}

/** Show screenshot container */
showScreenshots = function() {
	/*$("#feature_selector_item_screenshots").blur();*/
	
	if (screenshotGalleryInitialized == false) {
		$.getJSON("javascript/ui/data/screenshot_gallery.json", initScreenshotGallery);
	}
	
	$("#feature_screenshots").slideToggle("slow", reflectImages);
}

/** Hide screenshot container */
hideScreenshots = function() {
	/*$("#feature_selector_item_screenshots").blur();*/
	$("#feature_screenshots").slideToggle("slow");
}

/** PNG fix for ie6 */
fixIE6alphaTransparency = function() {
	if (isIE && browserVersion==6) {
		$("img").each(pngfix);
	}
}

/** Create "pages" for top_content */
createTopPages = function() {
	$("#top_jcarousel").jcarousel({
		visible:3
	});
}

/** Fetch twitter messages */
fetchTweets = function() {
	$("#bottom_tweets").tweet({
		username:"openSUSEhu",
		count:4
	});
}

/** Some style to list items on top of page */
formatContentLists = function() {
	$(".topcontent_list li").prepend("&raquo;&nbsp;");
}

/** Create sliding labels */
slideLabels = function() {
	$(".slider label").each(function() {
		var restingPosition = "5px";
		
		$(this).css({"left": restingPosition});
		
		var inputval = $(this).next().val();
		
		/* grab the label width, then add 5 pixels to it */
		var labelwidth = $(this).width();
		var labelmove = labelwidth + 5 + "px";
		
		/* onload, check if a field is filled out, if so, move the label out of the way */
		if (inputval !== '') {
			$(this).stop().animate({ "left":"-" + labelmove }, 1);
		}
		
		/* if the input is empty on focus move the label to the left */
		/* if it's empty on blur, move it back */
		$("input, textarea").focus(function() {
			$(this).addClass("activeinput");
			var label = $(this).prev("label");
			var width = $(label).width();
			var adjust = width + 5 + "px";
			var value = $(this).val();

			if (value == '') {
				label.stop().animate({ "left":"-" + adjust }, "fast");
			} else {
				label.css({ "left":"-" + adjust });
			}
		}).blur(function() {
			$(this).removeClass("activeinput");
			var label = $(this).prev("label");
			var value = $(this).val();

			if (value == '') {
				label.stop().animate({ "left": restingPosition }, "fast");
			}	
		});
	});
}

/** Load bottom left top content from json data */
fillBottomLeftTopContent = function(data) {
	var markup;
	
	$("#bottom_left_top").html("<h3>hírek</h3>");
	
	/* convert json string to markup */
	$.each(data, function(i, bottom_left_top_item) {
		markup =
			"<div id=\"bottom_left_top_" + i + "\" class=\"bottom_left_top_item\">" +
			"<h4>" + bottom_left_top_item.title + "</h4>" +
			bottom_left_top_item.content +
			"</div>";
		$("#bottom_left_top").append(markup);
	});
	
	bottomLeftContentFilled = true;
}

/** Load bottom left top content */
loadBottomLeftTopContent = function() {
	if (!bottomLeftContentFilled) {
		$.getJSON("javascript/ui/data/bottomleft_content.json", fillBottomLeftTopContent);
	}
}

/** Create fancy buttons */
formatButtons = function() {
	$(":button").attr("class","btn");
	$(".btn").each(function() {
		$(this).html("<span><span>" + $(this).text() + "</span></span>");
	});
}

/** Init roadmap */
initRoadmap = function() {
	var theme = Timeline.ClassicTheme.create();          
	theme.firstDayOfWeek = 1;

	var eventSource = new Timeline.DefaultEventSource();
    var bandInfos = [                                    
        Timeline.createBandInfo({                        
            width:          "60%", 
            intervalUnit:   Timeline.DateTime.MONTH,
            intervalPixels: 200,                         
            date:           new Date(),                  
            eventSource:    eventSource,
            theme:          theme
        }),
        Timeline.createBandInfo({
            width:          "40%",
            intervalUnit:   Timeline.DateTime.WEEK,
            intervalPixels: 200,
            eventSource:    eventSource,
            date:           new Date(),
            theme:          theme
        })
    ];
    bandInfos[0].syncWith = 1;
    bandInfos[0].highlight = false;

    timeline = Timeline.create(document.getElementById("feature_roadmap"), bandInfos, Timeline.HORIZONTAL);
    timeline.loadXML("javascript/ui/data/opensuse.xml", function(xml, url) {
        eventSource.loadXML(xml, url);
    });
    
    roadmapInitialized = true;
}

/** Show roadmap */
showRoadmap = function() {
	$("#feature_selector_item_roadmap").blur();
	
	if (roadmapInitialized == false) {
		initRoadmap();
	}
	
	$("#feature_roadmap").slideToggle("slow");
}

/** Hide roadmap */
hideRoadmap = function() {
	$("#feature_selector_item_roadmap").blur();
	$("#feature_roadmap").slideToggle("slow");
}

/** Show videos */
showVideos = function() {
	$("#feature_selector_item_video").blur();
	$("#feature_video").slideToggle("slow");
}

/** Hide videos */
hideVideos = function() {
	$("#feature_selector_item_video").blur();
	$("#feature_video").slideToggle("slow");
}

/** External links */
findExternalAnchors = function() {
	$("a, .tweet_list a").each(function() {
		var href = $(this).attr("href");
		if (!"opensuse\.hu".match(href)) {
			$(this).attr("class","external");
		}
	});
	/** External links in new window */
	$("a.external:not(#fancybox-outer a)").click(function() {
		var href = $(this).attr("href");
		window.open(href);
		return false;
	}); 
}

/** main */
$(document).ready(function() {
	browserDetection();
	fixIE6alphaTransparency();
	createTopPages();
	slideLabels();
	loadBottomLeftTopContent();
	formatContentLists();
	formatButtons();
	fetchTweets();
	initRoadmap();
	hideRoadmap();
	findExternalAnchors();
	$("#ordermediaform_callback_container").hide();
	
	
	/** Screenshots */
	$("#feature_selector_item_screenshots").toggle(
		function(event) {
			showScreenshots();
		},
		function(event) {
			hideScreenshots();
		}
	);
	
	/** Video */
	$("#feature_selector_item_video").toggle(
		function(event){
			showVideos();
		},
		function(event){
			hideVideos();
		}
	);
	
	/** Roadmap */
	$("#feature_selector_item_roadmap").toggle(
		function(event) {
			showRoadmap();
		},
		function(event) {
			hideRoadmap();
		}
	);
	
	/** Contact items */
	$(".contact_item").click(function(){
		var itemname = $(this).attr("id").replace("contact_","");
		var itemdescname = "contact_description_" + itemname;
		$(".contact_item_description").hide();
		$("#" + itemdescname).show();
	});
});

/** Hide order media form after submit */
orderMediaCallback = function() {
	$("#ordermediaform_callback_container").html("Kérését rögzítettük, hamarosan felvesszük Önnel a kapcsolatot.");
	$("#ordermediaform_container").hide();
	$("#ordermediaform_callback_container").show();
}

/** Check required fields on order media form */
checkOrderMediaValues = function() {
	var retcode = false;
	
	if (document.getElementById("ordermedia_name").value=="") {
		alert("Kérjük adja meg nevét!");
	} else if (document.getElementById("ordermedia_email").value=="") {
		alert("Kérjük adja meg email címét!");
	} else if (document.getElementById("ordermedia_q").value==0) {
		alert("Kérjük válassza ki az igényelt mennyiséget!");
	} else if (document.getElementById("ordermedia_atv").value==0) {
		alert("Kérjük válassza ki az átvétel módját!");
	} else {
		retcode = true;
	}
	
	return retcode;
}

/** Create a fake tartget for order media form */
createFakeTarget = function() {
	var faketarget = document.createElement("iframe");
	faketarget.setAttribute("id", "ordermedia-faketarget");
	faketarget.setAttribute("name", "ordermedia-faketarget");
	
	document.getElementById("faketarget_container").appendChild(faketarget);
}

/** Submit order media form */
orderMediaSubmit = function() {
	if (checkOrderMediaValues()) {
		createFakeTarget();
		var orderMediaForm = document.getElementById("ordermediaform");
		orderMediaForm.action = "https://spreadsheets.google.com/formResponse?formkey=dF92Rk9ueWFuYlJJNmg0dl80TTQ4bVE6MA";
		orderMediaForm.target = "ordermedia-faketarget";
		orderMediaCallback();
		return true;
	}
}

/** Check required fields */
checkSoftwareSearchValues = function() {
	var F = document.getElementById("softwaresearchform");
	var retcode = false;
	
	if (F.q.value=="") {
		alert("Kérjük adja meg a keresett csomag nevét!");
	} else {
		retcode = true;
	}
	
	return retcode;
}

/** Submit package serch form */
softwareSearchSubmit = function() {
	var F = document.getElementById("softwaresearchform");
	if (checkSoftwareSearchValues()) {
		F.submit();
	}
}
