//JavaScript Document
/*global window */
/*global $j */
/*global initTAB*/
/*global CKEDITOR */
/*global location */

// JavaScript Document
// common site wide code
var $j = jQuery.noConflict(); //Jquery compatibility mode
var tipOffset = [];
var parentItemSize = [];
var toolTipPosition = [];
var toolTipSize = [];
function notFunc(){};
var ieVersion = 0;

$j(document).ready(function() 
{
	//check browser version and alert if using ie 6 or older
	var thisBrowserVersion = 0;
	if ($j.browser.mozilla) 
		{
		thisBrowserVersion = $j.browser.version.substr(0,1);
		$j('body').addClass("moz"+thisBrowserVersion);	
	 	} 
	if ($j.browser.msie) {
		thisBrowserVersion = Math.floor($j.browser.version);
		ieVersion = thisBrowserVersion;
		browserVersionString = thisBrowserVersion.toString();
		$j('body').addClass("ie"+browserVersionString);	
		if (thisBrowserVersion <= 6) {
		alert("You appear to be using a version of Internet Explorer 6 or older, this site only works in Internet explorer 7 or above. Please upgrade your browser before using this site.");
			}
			
	 }
	

	 
	
	$j(".inputClear").bind("focus", function() {
			if ($j(this).val() == $j(this).attr("title")){
				$j(this).val("");
			}
	});

	$j(".inputClear").bind("blur", function() {
		if ($j(this).val() == "") {
			$j(this).val($j(this).attr("title"));
		}
	});
	
	//Add search remove text on focus
	$j("input[name='searchTerm']").bind('focus', function() {
										var tester =$j(this).val();
										if (tester == "Search" || tester == "Search..."){
											$j(this).val("");
											}
										});
	//Add search add text on blur
	$j("input[name='searchTerm']").bind('blur', function() {
										var tester =$j(this).val();
										if (tester == ""){
											$j(this).val("Search");
											}
										});
	
	//Add tooltip frame if not already there
	if ($j("#toolTipContainer") != ""){
	$j("body").prepend('<div id="toolTipContainer"><div id="toolTip" class="tooltip"><div id="toolTipTitle"><h3 class="heading7"></h3></div><div id="toolTipBody"></div></div><div class="toolArrowBot">&nbsp;</div></div>');
	}
	
	//Set up tooltips
	$j("#toolTipContainer").bind("mouseenter", function () {
		$j("#toolTipContainer").show();

		});
	
	$j("#toolTipContainer").bind("mouseleave", function() {												 
		$j("#toolTipContainer").clearQueue();
		$j("#toolTipContainer").hide();

		});
	
	
	$j('.hasTipTop').bind("mouseenter", function() {	
			
		$j("#toolTip > #toolTipTitle > h3").html($j(this).attr("tipTitle"));
		$j("#toolTip > #toolTipBody").html($j(this).attr("tipDescription"));
		toolTipSize[0] = $j("#toolTipContainer").width();
		toolTipSize[1] = $j("#toolTipContainer").height();
		$j("#toolTipContainer > div.toolArrowBot").width(toolTipSize[0]+"px");
		tipOffset = $j(this).offset();
		parentItemSize[0] = $j(this).width();
		parentItemSize[1] = $j(this).height();
		toolTipPosition[0] = tipOffset.left + (parentItemSize[0]/2);
		toolTipPosition[0] = toolTipPosition[0] - (($j("#toolTipContainer").width()/2).toFixed());
		toolTipPosition[1] = tipOffset.top + (parentItemSize[1]/2);
		toolTipPosition[1] = (toolTipPosition[1] - toolTipSize[1])-10;
		if(ieVersion!=0){
			
			toolTipPosition[1] = toolTipPosition[1] - 30;
			
			
			}

		$j("#toolTipContainer").css("left",toolTipPosition[0].toFixed()+"px");
		$j("#toolTipContainer").css("top",toolTipPosition[1].toFixed()+"px")
		$j("#toolTipContainer").pause(400).show();

		});
	
	$j('.hasTipTop').bind("mouseleave", function() {												 
		$j("#toolTipContainer").clearQueue();
		$j("#toolTipContainer").hide();

		});
	
	
	//$j('.hasTipRight').tooltip({ position: "center right", opacity: 1, offset:[0, 12], layout: '<div><div class="toolArrowLeft"></div></div>'});
   	//$j('.hasTipTop').tooltip({ position: "top center", opacity: 1, offset:[-8, 0], layout: '<div><div class="toolArrowBot"></div></div>'});
	
	//$j(function(){$j('form.jqTrans').jqTransform({imgPath:'css/'});});
	
	//Setup Menu
	var pathName = window.location.pathname;
	var pathNameArray = pathName.split("/");
	var LenOfPathNameArray = pathNameArray.length;
	//alert(LenOfPathNameArray);
	
	
	$j('#parentMenuUL').find('a.topLevel').removeClass("menuSelected");
	if (LenOfPathNameArray >= 2) {
		if (pathNameArray[1] == "pages"){
			var tmpItem = "a.topLevel[rel="+ pathNameArray[2] +"]";
			$j('#parentMenuUL').find(tmpItem).toggleClass("menuSelected");
			}
			else if (pathNameArray[1] == "index.html")
			{
			}
			else
			{
			var tmpItem = "a.topLevel[rel="+ pathNameArray[1] +"]";
			$j('#parentMenuUL').find(tmpItem).toggleClass("menuSelected");
			}
	
	}

	if ($j("#parentMenuUL").length){

		var browserOffset = 42; 					 
		if ($j.browser.msie){
			browserOffset = 84;
			}	
	
		var parentPositionTop = $j("#parentMenuUL").offset().top;
	
		$j("ul.withSecond>li.hasChild").bind("mouseover", function() {
			$j(this).find("ul.thirdLevelUL").css("display","block");											  
			var myoffset = $j(this).find("ul.thirdLevelUL").offset();	
			$j(this).find("ul.thirdLevelUL").removeAttr("style");											  
			currentULTop = 0;
			if(myoffset !=null){
			var currentULTop = myoffset.top;
			}
			var menuTop = currentULTop - parentPositionTop;
			menuTop = (menuTop*-1)+browserOffset;
			$j(this).unbind("mouseover");
			$j(this).find("ul.thirdLevelUL").css("top",menuTop+"px");
		
		});
	};

/*$j('html').show();*/

});


/*!
 * jQuery queueFn - v0.6 - 06/21/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

$j.fn.pause = function(duration) {
    $j(this).animate({ dummy: 1 }, duration);
    return this;
};


function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/*! NOTE Alfresco must be running on port 8080 for the callback functionality to work
 */
function editContentLinkBack(divType, divName, parent_path, form_instance_file, link_text, link_class){

  if(!link_text){link_text='Edit Content';}
  if(!link_class){link_class='editContent';}
	  
  var urlStr = location.href;
  //strip the ip address out of the preview url and then replace all the - with . 
  var previewIP = urlStr.substring(urlStr.lastIndexOf('sandbox.') + 8, urlStr.indexOf('.ip'));
  var ip = previewIP.replace(/-/g, '.');

                var editLinkStr = '<div class=\"' + link_class + '\">\r<a href=\"http://' + ip + ':8080/alfresco/wcservice/sage/editcontent?path=' 
							+ parent_path + '/' +
							form_instance_file + '\" target=\"_blank\">'+ link_text + '</a>\r</div>'
				
				// decide whether to append to div id or div class section.
				var div;
				if (divType == 'class') {
					div = "." + divName;
				} else {
				    div = "#" + divName;
				}
				
                if (urlStr.indexOf('alfrescodemo') != -1) {

                                //insert node for edit link into the dom just before the div id passed in if url is in preview mode
                                $j(div).before(editLinkStr);

                }
  
}

function updatePreviewUrls() {
    // Create a dialog instance
    var previewDialog = $j('<div></div>').html('This link unavailable in preview mode..');
    previewDialog.dialog({
           autoOpen: false,
           title: 'Link Unavailable!',
           modal: true,
           resizable: false,
           height: 120,
           width: 250,
           stack: false,
           closeOnEscape: true,
           buttons: { "Ok": function() { $j(this).dialog("close"); } },
           draggable: false
    });

           
    // Parse through all links once (we will try to do all our processing in 1 pass)
    $j("body a").each(function(index) {
           // Check if the link contains "?" and doesn't contain ".html" ... or it has a clas of "skipPreview" - this should catch 99% of links
		   var attr = $j(this).attr("href");
		   var test1 = -1;
		   var test2 = -1; 
				 
		   if (typeof attr !== 'undefined' && attr !== false) {
				 var test1 = $j(this).attr("href").indexOf("?"); 
		   		 var test2 = $j(this).attr("href").indexOf(".html"); 
		   }
		   
		   var test3 = $j(this).hasClass("skipPreview");
		  // console.log(test1+" "+test2+" "+test3);
		   
			if ( (test1 > -1 && test1 < 0) || test3 ) {
                  $j(this).bind("click", function() {
                        previewDialog.dialog('open');
                        return false;
                  });
           }
    });
    // Parse forms separately (currently stops all forms from being submitted)
    $j("form").each(function(index) {
           $j(this).bind("submit", function() {
                  previewDialog.dialog('open');
                  return false;
           });
    });
}

function rateCookie(questID, rateID){
	//alert(questID);
	$j.cookie("rate_"+questID, rateID);
	}
	
function get_cookies_array() {
	    var cookies = { };
	 
	    if (document.cookie && document.cookie != '') {
	        var split = document.cookie.split(';');
	        for (var i = 0; i < split.length; i++) {
	            var name_value = split[i].split("=");
				var nameComp = (name_value[0].replace(/^ /, '')).substr(0,5);
				if(nameComp == "rate_"){
					name_value[0] = name_value[0].replace(/^ /, '');
					name_value[0] = name_value[0].substr(5,name_value[0].length);
					cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
				}
	        }
	    }
	 
	    return cookies;
	    
}	

function moveToTop(event, ui){
	$j('html, body').animate({ scrollTop: 0 }, 0);
}


function getTabFromURL() {
	var tmpURL = window.location.href,
		splitURL = tmpURL.split('/'),
		lastItem = splitURL[splitURL.length-1],
		startStr = lastItem.search('#tabs-'),
		tmpArray = [],
		returnVal;
		if(startStr != -1){
			lastItem = lastItem.substr(startStr, (lastItem.length - startStr));
			tmpArray = lastItem.split('-');
			returnVal = parseInt(tmpArray[tmpArray.length-1], 10);
		} else {
			returnVal = 1;
		}
		return returnVal;
}

function initTAB() {
	$j(function () {$j('#tabs').tabs({
		cookie: {},
		show: moveToTop,
		select: getTabFromURL()
		}); });
}


function updateRate(){
      
			var rateCookies = get_cookies_array();	
			var testValue
			for(var t in rateCookies) {
				if (rateCookies[t] == "useful") {
					testValue = "#"+t;
					$j(testValue).find('a.useful').toggleClass('useful').toggleClass('usefulClicked');
					$j(testValue).find('a.notUseful').hide();
					}
				if (rateCookies[t] == "notUseful") {
					testValue = "#"+t;
					$j(testValue).find('a.notUseful').toggleClass('notUseful').toggleClass('notUsefulClicked');
					$j(testValue).find('a.useful').hide();
					}
					
			}
						  
}
