// RTC Factory global javascript

var myTitle = new Array();
myTitle["#rtczap4"] = "RTC Zap 4";
myTitle["#rtcvoip"] = "RTC VoIP";
myTitle["#rtcipcentrex"] = "RTC IP Centrex";
myTitle["#rtcconnect"] = "RTC Connect";
myTitle["#click2call"] = "RTC Click 2 Call";
myTitle["#devicedirector"] = "DeviceDirector";
myTitle["#rtcaccess"] = "RTC Access";
myTitle["#zapenterprisetoolbar"] = "Zap Enterprise Toolbar";
myTitle["#zapgadget"] = "Zap Gadget";

function fbs_click() {
	var u=location.href;
	var t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

//Ladda rätt submeny
var currentAnchor = null;
function loadSubpageContent() {
	
	if(currentAnchor != document.location.hash){
		currentAnchor = document.location.hash;
		//alert(currentAnchor);
		//if there is not anchor, the loads the default section
		if(!currentAnchor){
			//loadZap4page();
			//currentAnchor = "#rtczap4" || "#rtcvoip";
			if (masterDefault != "") {
				currentAnchor = masterDefault;
				var getRightSubMenu = "." + currentAnchor.substring(1) + "Link";
			if (masterHasSub && masterTitle != undefined)
			{
				document.title = masterTitle + ", " + myTitle[currentAnchor];
				$('ul#subPageMenu a' + getRightSubMenu).click();
			}}
		}
		else
		{
		//Creates the string callback.
			var splits = currentAnchor.split('&');
			//alert(splits);
			//Get the section
			var section = splits[0];
			delete splits[0];
			//Create the params string
			var params = splits.join('&');
			//alert(params);
			//var query = "page=" + section + params;
			var query = section + params;
			//alert(query);
			var getRightSubMenu = "." + currentAnchor.substring(1) + "Link";
			$(getRightSubMenu).click();
			if (masterHasSub)
			{
				document.title = masterTitle + ", " + myTitle[currentAnchor];
			}
		}
	}
}
function showAssistanceRequest(formData, jqForm, feedbackOptions) { 
    var queryString = $.param(formData); 
	$("#submitAssistance").hide();
	$("#processing").show();
    return true; 
} 
 
// post-submit callback 
function showAssistanceResponse(responseText, statusText)  { 
	if (responseText==1) {					
					//hide the form
					$("#assistanceForm").slideUp();
					//$('.assistance input').attr('disabled','false');
					$('.assistance .smallestH4').hide();
					$('.assistance .smallestH4').html("Thank you for your request.<br />We will get back to you as soon as possible.")
					$('.assistance .smallestH4').show();
					$('#assistanceForm').resetForm();
					//show the success message
					//$('.done').fadeIn('slow');
					
				//if process.php returned 0/false (send mail failed)
				} else alert('Sorry, unexpected error. Please try again later.');	
}

function fixEmail() {
	$(".email").attr("href", function() { 
		return "mailto:" + this.title + "@rtcfactory.com"; 
	});
}

$(document).ready(function(){
		$.ajaxSetup({cache:false});
		//var path = location.pathname.substring(6);
		var path = location.pathname.substring(1);
		var home = "/";
		$(".subpageMenu a[href='" + [path || home] + "']").parents("li").each(function() {   
				$(this).addClass("active");
		});
		//för ladda in default
		setInterval("loadSubpageContent()", 300);
		
		$('#headerInfo').innerfade({ speed: 750, timeout: 8000, type: 'sequence', containerheight: '145px' }); 
		
		//för ladda in rätt section/product per paket.
		
		$('#subPageMenu li a').click(function(){
									  
			//var toLoad = 'sub/'+$(this).attr('href')+' #productInfo';
			var toLoad = 'sub/'+$(this).attr('href').substring(4)+"?sub=1";
			var toLoadSub = toLoad.substring(0, toLoad.length - 10);
			//$('#productInfo').hide('fast',loadContent);
			loadContent();
			//$('#load').remove();
			//$('#wrapper').append('<span id="load">LOADING...</span>');
			//$('#load').fadeIn('normal');
			window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4).substring(4);
			$("#subPageMenu a").removeClass("activeSubMenuLink");
			$(this).addClass("activeSubMenuLink");
			function loadContent() {
				//$('#productInfo').load(toLoad,'',showNewContent())
				//start
				//$('#productInfo').show('normal',hideLoader());
				pos = $(this).attr("class");
				$("#infoBox").slideDown();
				$(".productInfoBox").html("<img src='images/loader.gif' alt='loading...' id='loadingContent' /> Loading content...");
				$("#productInfo").html("<img src='images/loader.gif' alt='loading...' id='loadingContent' /> Loading content...");
					$("#loadingContent").fadeIn('slow').animate({opacity: 1.0}, 300).fadeOut('slow', function(){
					$("#productInfo").load(toLoad, function() {
						$("#infoBox").animate({height: $("#productInfo").height()}, function(){
							$(".viewFeatures").hide();
							$("#productInfo").height();
							$(".viewFeatures").show();
							$("#infoBox").animate({height: $("#productInfo").height()});
							$(".productInfoBox").fadeIn("slow", function() {
								//$(".productInfoBox").html("<h4>Headline</h4>With pics here!");
								$(".productInfoBox").load("includes/php/"+toLoadSub.substring(4)+"SmallBoxRight.php", function() {
									fixEmail();
									$(".zap4Gallery").find("a").attr({rel:"zap4Screenshots"});
									$("a[rel='zap4Screenshots']").colorbox({transition:"elastic", contentCurrent:"{current} / {total}"});
								});
								$("#customerCase").load("includes/php/customerCase.php", function() {
									$("a[rel='softphone']").colorbox({transition:"elastic", contentCurrent:"{current} / {total}"});
								});
								$("#customerCase").fadeIn();
							});
						});
					});
				});
			//end
			}
			//Används inte
			/*function showNewContent() {
				$('#productInfo').show('normal',hideLoader());
			}
			function hideLoader() {
				$('#load').fadeOut('normal');
			}*/
			return false;
			
		});
		//Zebra styling
		$(".featuresTable tr").live("mouseover", function(){
			$(this).addClass("over");
		}).live("mouseout", function(){
			$(this).removeClass("over");
		});
		//Länkar för stora menyn
		$(".telecomPackage, .ispPackage, .rtcPackage, .dualHostPackage").click(function(){
			window.location = $(this).attr("id");
			return false;
		});
		$('.rtcPackages').hover(function(e) {
			$(this).find(".firstPageReadMore").hoverFlow(e.type, {
				'height': 'show',
				'marginTop': 'show',
				'marginBottom': 'show',
				'paddingTop': 'show',
				'paddingBottom': 'show' 
			});
			$(this).css({ "cursor":"pointer" });
		}, function(e) {
			$(this).find(".firstPageReadMore").hoverFlow(e.type, {
				'height': 'hide',
				'marginTop': 'hide',
				'marginBottom': 'hide',
				'paddingTop': 'hide',
				'paddingBottom': 'hide' 
			});
			$(this).css({ "cursor":"default" });
		});
		//Sidomenyn för de olika paketen
		$('.subpageMenu li').hover(function(e) {
			$(this).not(".active").hoverFlow(e.type, {
				'marginTop': '0px'
			}, 'fast');
			$(this).css({ "cursor":"pointer" });
		}, function(e) {
			$(this).not(".active").hoverFlow(e.type, {
				'marginTop': '9px'
			});
			$(this).css({ "cursor":"default" });
		});
		//Visa features tabellen om en sådan finns
		$(".viewFeatures", this).live("click", function(){
			$("#infoBox").css("height", "auto");
			$(".featuresTable tr:even").addClass("alt");
			$(".minFeaturesTxt, .regFeaturesTxt").slideToggle();
			//$(".features").slideToggle();
			$(".features").slideToggle("fast", function(){
				$("#infoBox").animate({height: $("#productInfo").height()}, function(){
					$("#productInfo").height();
					//$.scrollTo(".viewFeatures", 800);
					
				});
			});
		});
		$(".goToTop").live("click", function() {
			$.scrollTo(".package", 800);
		});
		var assistanceOptions = { 
        //target:        '#output1',   // target element(s) to be updated with server response 
        beforeSubmit:  showAssistanceRequest,  // pre-submit callback 
        success:       showAssistanceResponse,  // post-submit callback 
 
        // other available options: 
        url:       "php/process_assistance.php",         // override for form's 'action' attribute 
        type:      "post",        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        clearForm: true,        // clear all form fields after successful submit 
        resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
		};
		$("#assistanceForm").validate({
				errorLabelContainer: $('.assistanceError'),
				errorContainer: $('.assistanceError'),
				//errorLabelContainer: "p",
				meta: "validate",
				submitHandler: function(form) {
					//alert('hepp');
					$(form).ajaxSubmit(assistanceOptions);
					
				}
		});
		/*$("#submitAssistance").click(function () {
			//return false;
		});*/
		$("#faqQuestions > li").click(function(e) {
        	// click events
			//var an = $(this).attr("href");
			var an = $(this).find("a").attr("href");
	        //var an = "#" + qu.replace("q","a");
			//alert(an);
			//$.scrollTo(an, 800);
			$.scrollTo(an, {duration: 800, axis:"y", onAfter:function(){
				$(an).find("h4").animate({ backgroundColor: '#fbfca8' }, 200).animate({ backgroundColor: '#fff' }, 200).animate({ backgroundColor: '#fbfca8' }, 200).animate({ backgroundColor: '#fff' }, 350);
				//alert(an);
				}
			});
			e.preventDefault();
	    });
		$(".return-top").click(function(e) {
			$.scrollTo(".contactBox", {duration: 800, axis:"y"});
			e.preventDefault();
		});
		$(".showDidCountries").live("click", function() {
			$(".didCountriesIntro").hide();
			$(".didCountries").addClass("rightSideBox").slideDown();
		});

		//$(".email").each(function () { $(this).attr("href", "mailto:"+"title"+""); });
		/*$(".email").attr("href", function() { 
          return "mailto:" + this.title + "@rtcfactory.com"; 
        });*/
		fixEmail();
		//Visa login overlay
		$(".partnerLogIn").click(function(){
			$("#partnerBox").modal({onOpen: function (dialog) {
				dialog.overlay.fadeIn('fast', function () {
					dialog.data.hide();
					dialog.container.fadeIn('slow', function () {
						dialog.data.fadeIn('slow');
						$('#partnerID').focus(); 
					});
				});
			},overlayClose:true,
			minHeight:230,
			minWidth:300,
			maxWidth:310,
			onClose: function (dialog) {
				dialog.data.fadeOut('fast', function () {
					dialog.container.slideUp('fast', function () {
						dialog.overlay.fadeOut('slow', function () {
							$.modal.close();
						});
					});
				});
			}});
		});
		//Overlay ruta för de olika teknikerna i FAQ:sidan
		$(".technologyBox").live("click", function(){
			var srcClass = $(this).attr('id');
			//alert(srcClass);
			var src = srcClass.substring(0, srcClass.length - 3);
			$("#technologyModalBoxContent").load("php/" + src + ".php");
			$("#technologyModalBox").modal({onOpen: function (dialog) {
				dialog.overlay.fadeIn('fast', function () {
					dialog.data.hide();
					dialog.container.fadeIn('slow', function () {
						dialog.data.fadeIn('slow');
						//$("#technologyModalBox").find("a").addClass("modal-close");
						});
					});
				},
				overlayClose:true,
				minHeight:450,
				maxHeight:650,
				minWidth:820,
				maxWidth:830,
				onClose: function (dialog) {
				dialog.data.fadeOut('fast', function () {
					dialog.container.slideUp('fast', function () {
						dialog.overlay.fadeOut('slow', function () {
							$.modal.close();
						});
					});
				});
			}});
		});
		$("#partnerLoginBtn").click(function() {
			alert("Currently under maintenance, please try again later.");
		});
		$("a[rel='illustrations']").colorbox({transition:"elastic", contentCurrent:"{current} / {total}"});
    }); 