// Configs
$main_js = "/css/1.2/js/main.js";
$blockUI_js = "/css/1.2/js/jquery.blockUI-2.0.7.js";
var growlerEnabled = false;

// setup jquery to use $j reference
var $j=jQuery.noConflict();

// blockUI overrides


// Hide instruction text for password field
function txt2pwd(obj, pwd){
  obj.style.visibility = "hidden";
  document.getElementById(pwd).focus();
}

// Display instruction text for password field
function pwd2txt(obj, txt){
  if(obj.value.length==0){
    document.getElementById(txt).style.visibility = "visible";
  }
}

// Display instruction text [str] if field is blank
// Clear instruction text if field is clicked
function resetField(obj,str){
  if(obj.value.length==0){
    obj.value=str;
    return;
  }
  if(obj.value==str){
    obj.value="";
  }
}

// Tab switcher - initialisation 
// tabContainerId = ID of tab container
function initTabs(tabContainerId){
  var tabContainer = document.getElementById(tabContainerId); 
  if (!tabContainer) return;

  var divSet = tabContainer.getElementsByTagName('div');
  var firstTabFlag=0;
  for (var i=0; i<divSet.length; i++) {
    if (divSet[i].className=='tabcontent') {
      if (!firstTabFlag) {
        divSet[i].className='';
        firstTabFlag=1;
      } else {
        divSet[i].className='hidden';
      }
    }
  }
}

// Tab switcher
// container = ID of tab container, must be used if more than one tab module is used on page (optional usage if only one tab module is displayed on a page )
// tab = ID of tab (mandatory)
function showTab(tab, container){
  if(typeof(container)=='undefined') {
    container='';
  }
  var i=1;
  do{
    document.getElementById(container+"tab"+i).className = "tab";
    document.getElementById(container+"tab"+i+"content").style.display="none";
    i++;
  }
  while(document.getElementById(container+"tab"+i));
  document.getElementById(container+tab+"content").style.display="block";
  document.getElementById(container+tab).className = "activeTab";
}


// replace the HTML Call-to-action box by a flash movie using the Vodafone corporate font
function replaceCTABox(){
  var cta = document.getElementById('ctaLayer');
  var ctaMod = cta.parentNode;
  if (ctaMod!=null && cta!=null) {
    var h1,s,a,l,u,t; h1=s=a=l=u=t='';
    if (cta.getElementsByTagName("h1")[0]!=null) h1= encodeURI(cta.getElementsByTagName("h1")[0].innerHTML);
    if (cta.getElementsByTagName("p")[0]!=null) s = encodeURI(cta.getElementsByTagName("p")[0].innerHTML);
    var w = cta.offsetWidth;
    var h = cta.offsetHeight;
    
    var so = new SWFObject("/css/1.2/swf/calltoactionbox.swf", "calltoactionbox", w, h, "8", "#F10000");
    so.addVariable("head", h1);
    so.addVariable("sub", s);
    so.addVariable("boxw", w);
    so.addVariable("boxh", h);
    
    var a = cta.getElementsByTagName("a")[0];
    if (a!=null) {
    var l = encodeURI(a.innerHTML);
    var u = encodeURI(a["href"]);
    var t = a["target"];
      
      so.addVariable("link", l);
      so.addVariable("url", u);
      so.addVariable("target", t);
    }   
  }
	so.addParam("wmode", "transparent");
  so.write("ctaLayer");
} // replaceCTABox


// replace the Submit-Button with a styled JS-Button
function replaceButton() {
	var button;
	
	if(arguments.length == 1){
		var button = document.getElementById(arguments[0]);
		//if(!button) return;		
	}
	
	if(arguments.length == 2){
		var form = document.getElementById(arguments[0]);		
		var button = document.getElementById(arguments[1]);	
		//if(!form && !button) return;
	}	
	
	var text = button["value"];
	var color = button.className; // e.g. inputBtnRed
  
  // if multiple classes on input element - this only handles the first class!
  if(color.indexOf(" ")!= -1){
    var classes = color.split(" ");
    color = classes[0];
  }
  
	color = color.slice(8); // e.g. Red
	switch (color) {
		case "Red":
		case "Purple":
		case "Grey":
		case "GreyOnRed":
		case "Purple":
    case "RedMedium":
    case "GreyMedium":
		break;
		default:
		color = "Red";
		}

		button.className = "hide";
		button.id = "";		
		if(arguments.length == 1){
			var buttonObjStr = "<a href='#' id='"+arguments[0]+"' class='textBtn"+color+" formBtn'><span>"+text+"</span></a>";
		}		
		if(arguments.length == 2){
			var buttonObjStr = "<div class=\"formButtons\"><a href=\"#\" onclick=\"document.getElementById('"+arguments[0]+"').submit();return false;\" id=\""+arguments[1]+"\" class=\"textBtn"+color+" formBtn\"><span>"+text+"</span></a></div>";
		}				
	document.write(buttonObjStr);   
} // replaceButton

// fold and unfold option sections on shopping cart page
function scFold(optId) {
  var optHeader = document.getElementById(optId);
  if (optHeader!=null) {
    var pattern = new RegExp("(^|\\s)"+optId+"(\\s|$)");
    var trList = document.getElementsByTagName('tr');
    if (optHeader.className=="scOptShow") {
      // hide options
      for (i=0; i<trList.length; i++) {
        if (pattern.test(trList[i].className)) {
          trList[i].className=optId+" hidden";
        }
      }
      optHeader.className="scOptHide";      
    } else {
      // show options
      for (i=0; i<trList.length; i++) {
        if (pattern.test(trList[i].className)) {
          trList[i].className=optId;
        }
      }     
      optHeader.className="scOptShow";      
    }
  }
} // scFold

function deepLink() {
 var url;
 var hashPos;
 var tabFound;
 var tab;
 
 // Get current URL
 url = location.href;
 
 // Set index of #
 hashPos = url.indexOf("#");
 
 // Check its a tab not expander
 if (url.indexOf("tab") > 0) { 
  tabFound = true;
 }
 // Check if # exsits and its a tab call
 if (hashPos > 0 && tabFound) { 
   // Get tab name and format correctly (i.e. #tab3content becomes tab3)
   tab = url.substring(hashPos+1).replace(/content/,"");
   // Show tab
   showTab(tab);
 }
}


// Start Knowledge Base
// formats response, returns answer html to be displayed
var formatAnswerDisplay = function( response ) {
	var display = '<img src="http://www.vodafone.co.nz/css/1.2/img/vodafone_logo.gif" alt="Vodafone" class="lightVLogo"/>'
	+ '<div class="answerTools">'
	+ '<div class="print"><a href="' + response.url_print + '" target="_blank" class="printBtn printBtnTrigger">Print answer</a>&nbsp;&nbsp;'
	+ '<a href="' + response.url_email + '"  class="emailBtn emailBtnTrigger">Email answer</a><br /></div>'
	+ '<div class="rate"><b>Was this helpful?</b>'
	+ '<form id="rating"><div>'
	+ '<a href="' + response.url_rating_yes + '" class="textBtnGrey ratingYes ratingYesTrigger"><span>Yes</span></a>'
	+ '<a href="' + response.url_rating_no + '" class="textBtnGrey ratingNo ratingNoTrigger"><span>No</span></a>'
	+ '</div><div class="clear"></div></form>'
	+ '<div class="notifyMe"><h4>More help required?</h4>'
	+ '<form method="get" name="_notif" id="_notif">'
	+ '<div><a href="' + response.url_notify + '" class="notifyButton btnText">Notify me by email if this changes</a><br />'
	+ '<a href="http://vodafonenz--upgrade--pro.custhelp.com/cgi-bin/vodafonenz.cfg/php/enduser/ask.php"  class="btnText">Email customer support</a>'
	+ '</div></form></div></div></div><div class="answerWrapper">'
	+ '<div class="textWrapper"><h2>' + response.summary + '</h2>'
	+ '<div id="soln">' + response.answer_content +'</div>'
	+ '<div id="alsoviewed">';
	
	if( response.has_attachments ) {
		display += '<h3> File Attachments </h3><ul>';
		for (var i = 0; i < response.attachments.length; i++ ) {
			attachment = response.attachments[i];
	    	display += '<li><a href="' + attachment.link + '" target="_blank" class="plain"><img border="0" src="' + attachment.url_icon + '" alt="' + attachment.title + '"/> ' + attachment.name + '</a></li>';
	    }
		display += '</ul>';
    }
    
	display += '<h3>Users who viewed this answer have also viewed</h3><ul>';
	for (var i = 0; i < response.related_answers.learned.length; i++ ) {
		answer = response.related_answers.learned[i];
		display += '<li><a class="underline" href="' + answer.url + '">' + answer.title + '</a></li>';
	}
	
	display += '</ul></div></div></div>';
	
	return display;
};

// snippet from http://www.vodafone.co.nz/vf-apps/shop/css/1.2/js/shop_nz.js
function blockUI(div){
	$j.blockUI({ message: $j(div) });
	$j(div).removeClass("hidden").addClass("show");    
}

function unblockUI(div) {
	$j(div).removeClass("show").addClass("hidden");
	$j.unblockUI();
}
// end snippet

function addBlockUIJS(){
	var script = document.createElement("script");
	$j(script).attr("type", "text/javascript");
	$j(script).attr("src", $blockUI_js);
	$j("head").append(script);
}
// End Knowledge Base

// Start feedback mechanism
var form_expanded = false;
var thumb_clicked = false;
var submit_clicked = false;
// expand the form
function expandForm(){
	if(form_expanded == false){
	$j("#feedback_content").animate({
			height: 250												
		}, 500);	
	// remove click event from thumbs
	$j("#thumbs_up, #thumbs_down").unbind("click");
	$j("#thumbs_up, #thumbs_down").click(function(){
		return false;
	});
	$j("#thumbs_up, #thumbs_down").css("cursor","default");
	form_expanded = true;
	}
}

// retract the form
function retractForm(){
	if(form_expanded == true){
		$j("#feedback_content").animate({
			height: 0
		}, 500);	
	bindThumbs();
	bindSubmit();
	$j("#thumbs_up, #thumbs_down").css("cursor","pointer");
	$j("#comments").val("");
	form_expanded = false;
	submit_clicked = false;
	thumb_clicked = false;
	}
}

// bind click event to thumbs
function bindThumbs(){
	$j("#thumbs_up, #thumbs_down").click(function(){
	// double click protection prevents multiple ajax requests
		if(thumb_clicked == false){
			// display the ajax indicator
			updateCopy("Let us know what you think of this page?", "<img src='/img/feedback/ajax-indicator-sm.gif' />");			
			var rating = $j("#"+this.id).text();			
			// time delay before firing request
			var t = setTimeout(function() {			
				$j.ajax({
					dataType: 'jsonp',
					jsonp: 'ajaxJSONCallbackRating',  	
					url: document.location.protocol+'//feedback.vodafone.co.nz/json.php?rating='+rating+'&url='+document.location.href
				});
			}, 500); 						
			thumb_clicked = true;
			return false;
			}
		else return;
	});		
}

// bind click event to submit
function bindSubmit(){
$j("#send_comment").click(function(){
		// some basic validation
		var comments = $j("#comments").val();
		if(comments.length > 0){				
			if(submit_clicked == false){
				submit_clicked = true;
				// show ajax indicator
				$j("#ajax_indicator_lg").css("display", "block");
				// time delay before firing request
				var s = setTimeout(function() {			
					$j.ajax({
						dataType: 'jsonp',
						jsonp: 'ajaxJSONCallback',  	
						url: 'http://feedback.vodafone.co.nz/json.php?comments='+comments
					});
				}, 5000); 	
				return false;
			}
			else{
				$j("#send_comment").unbind("click");
				$j("#send_comment").click(function(){
					return false;
				});
			}		
		}
		else{
			// send "cancel" to server so the session is destroyed
			$j.ajax({
				dataType: 'jsonp',
				jsonp: 'ajaxJSONCallback',  	
				url: 'http://feedback.vodafone.co.nz/json.php?cancel=true'
			});	
		}			
		return false;
});
}

function bindCancel(){
	// cancel button clicked	
	$j("#cancel").click(function(){
	// send "canel" to server so the session is destroyed
		$j.ajax({
			dataType: 'jsonp',
			jsonp: 'ajaxJSONCallback',  	
			url: 'http://feedback.vodafone.co.nz/json.php?cancel=true'
		});	
		submit_clicked = true;
		thumb_clicked = false;	
		return false;
	});
}

// response copy
function updateCopy(header_copy, rating_copy){
	$j("#feedback_header strong.header").html(header_copy);
	$j("#feedback_rating").html(rating_copy);	
}

// display selected rating as highlighted thumb
function highlightThumb(good_rating){
	if(good_rating == true){
		$j("#thumbs_down").css("background-position", "left -18px").css("color","#929292");
		$j("#thumbs_up").css("background-position", "left 0px").css("color","#ffffff");
	}	
	else{
		$j("#thumbs_up").css("background-position", "left -18px").css("color","#929292");
		$j("#thumbs_down").css("background-position", "left 0px").css("color","#ffffff");		
	}
}

// json callback
function ajaxJSONCallback(data){		
	if(data.rating){
		var good_rating = data.rating == "Good" || data.rating == "good" ? true : false;
	}	
	if(data.rating_submitted == "true"){
		updateCopy("Thank you for your feedback", "You rated this page");
		highlightThumb(good_rating);
		expandForm();
	}	
	if(data.comments_submitted == "true" || data.cancel == "true"){	
		$j("#ajax_indicator_lg").css("display", "none");
		updateCopy("Many thanks for your feedback - we&lsquo;ll see what we can do", "");
		highlightThumb(good_rating);		
		retractForm();	
		var c_url = handleURL(data.url);	
		setCookie('VFNZ_feedback', c_url, data.rating);
	}
}

// get path from URL
function handleURL(val){
	var proto_dom = location.protocol+"//"+location.host;	
	var c_url = val.split(proto_dom);	
	return c_url[1];
}

// set cookie
function setCookie(c_name, c_url, c_rating){
	// Constant for FIFO, maximum URLS to keep in cookie (*2 for indexes)
	// I.E Currently allows 10 urls, which is 20 indexes
	var MAX_INDEX = 10 * 2;	
	var c_rating = c_rating == "Good" || c_rating == "good" ? 1 : 0;
	var count =0;
	// create a new cookie
	if(document.cookie.indexOf(c_name + "=") == -1){			
		var expires=new Date();
		// cookie expires in 30 days
		expires.setDate(expires.getDate()+30);		
		document.cookie=c_name+"=" +escape(c_url)+"|"+escape(c_rating)+";expires="+expires.toGMTString();
	}
	// append to existing cookie
	else{				
		// Get the cookie
		var old_cookie = getCookie(c_name);		
		// Split the cookie data into an array so we can use it
		old_cookie_data = old_cookie.split("|");			
		// FIFO: if cookie length is over the max, remove the first URL & rating
		if(old_cookie_data.length >= MAX_INDEX){
			old_cookie_data.splice(0, 2);
		}
		// Initialize new array for data to write to cookie
		new_cookie_data = Array();
		new_cookie_data.length = 0;	
		// Loop through all data currently stored in cookie
		for(var x = 0; x < old_cookie_data.length; x++){
			// Get the URL and rating
			url = old_cookie_data[x];
			rating = old_cookie_data[x+1];
			// Add URL and rating to to new cookie
			new_cookie_data.push(url);
			new_cookie_data.push(rating);			
			// Check if current URL exists in cookie
			if(url == c_url){
				// Remove the rating from array (as user is re-rating URL)
				new_cookie_data.splice(x, 2);
			}
			// Double incrementer for loop, this skips the rating (as each URL uses 2 array indexes)
			x = x+1;
		}
		// Add current URL and rating to new cookie
		new_cookie_data.push(c_url);
		new_cookie_data.push(c_rating);
		// Build new cookie
		new_cookie = new_cookie_data.join("|");
		// Write new cookie to disk
		document.cookie = c_name+"="+escape(new_cookie);		
	}
}

// get cookie
function getCookie(c_name){
	if(document.cookie.length > 0){
	//  need to exclude index files from URL - NEED TO DO # ALSO
		//var index_files = c_name.replace(/(index).(html|jsp|php)/g, "");		
		var c_start = document.cookie.indexOf(c_name + "=");// != -1 ? true : false;
		// var c_start = document.cookie.indexOf(index_files + "=") != -1 ? true : false;	
		if(c_start != -1){ 
			c_start = c_start + c_name.length+1; 
			c_end = document.cookie.indexOf(";",c_start);
			if(c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
  }
	return "";
}

// check cookie
function checkCookie(){
	old_cookie = getCookie('VFNZ_feedback');
	if (old_cookie != null && old_cookie != ""){		
		// split the contents
		old_cookie = old_cookie.split("|");
		var count = 0;
		var url;
		var rating;		
		var c_url = handleURL(document.location.href);
		// loop through split contents
		for(var x = 0; x < old_cookie.length; x ++){
			if((count%2) == 0)url = count;			
			if((count%2) == 1)rating = count;
			if(c_url == old_cookie[url]){
				var good_rating = old_cookie[rating] == 1 ? true : false;
				highlightThumb(good_rating);
				updateCopy("Many thanks for your feedback - we&lsquo;ll see what we can do", "");
			}
			count ++;
		}
	}
	else{
		return;
	}
}
// End feedback mechanism


// Handle mouse-over and link for modules with '.feature' class. JavaScript is awesome.
$j(document).ready(function () {
	// grab the href from the first anchor in the block and link to it on 'click'.
	$j(".modHover").bind("click",
		function (e) {
			var theLink = $j(this).find("a").eq(0).attr("href");
			window.location.href = theLink;
			e.stopPropagation();
		}
	);
	// set hover state for modules with '.feature' class
	$j(".modHover").bind("mouseenter",
		function () {
			$j(this).addClass("modHoverOver");
		});
	$j(".modHover").bind("mouseleave",
		function () {
			$j(this).removeClass("modHoverOver");
		}
	);
});

// tooltips
function makeTip(){
  // test if jquery tooltip plugin is present
  if($j.fn.tooltip){
    $j(".tip").tooltip({
      bodyHandler: function() {
        return $j($j(this).attr("href")).html();
     },
      showURL: false,
      left: 20,
      top:-19
    });

    // don't follow tooltip click
    $j(".tip").click(function(){
      return false;
    }); 
  }
  else{
    return;
  }
}

// DOM ready
$j(document).ready(function() {
	// deep linking
 	deepLink(); 
	// load growler
	if (growlerEnabled == true) {
		$j.getScript("/js/growler/growler.js");
	}
	
	// feedback mechanism
	checkCookie();
	bindThumbs();	
	bindSubmit();
	bindCancel();
  // tooltips
  makeTip();
/* 	// if kb links are present call function to include blockUI script														
	if($j(".kb_link_external").size() > 0){
		addBlockUIJS();
		$j(".kb_link_external").click( function() {
			scriptSrc = $j(this).attr('href') + ( /\?/.test( $j(this).attr('href') ) ? '&' : '?' ) +  'jsonp=1&format=json&callback=?';
				$j.getJSON(scriptSrc,
				function(data){
					$j('#kbWrapper').html( formatAnswerDisplay( data ) );
					blockUI($j("#kbIframe"));
				});
		return false;			
		});	
	}	
*/
});

// track "Go On Account" ads
$j(document).ready(function(){
	$j("[src$='shop-generic-banner-186x172.jpg']").click(function(){
		if(typeof(firstTracker) != "undefined"){
			firstTracker._trackEvent("Clicks", "Go On Account");
		}
	});
});

