var dialingLocation;
var msNumberOfLocations, msSummaryBoxBegin;

$(function() {
	$("#msPrivateCompanyName, #msPrivateContactName, #msPrivateContactNumber, #msPrivateContactEmail").change(function() {
		msUpdateFieldFromInput($(this).attr("id"), $(this).attr("id") + "Display");
	});
	
	$("#msSyncRoomHelp").qtip({
		content: msExplainSyncPopUp(),
		position: {
		  corner: {
			 target: 'leftTop',
			 tooltip: 'rightTop'
		  }
		},
		style: { 
			padding: 3,
			width: 260,
			background: '#F7F7F7',
			border: {
				width: 5,
				radius: 15,
				color: '#E6E6E6'
			},
			tip: 'rightTop'
		}
	});
	
	$("div.PendingQueueTableContainer table.PendingQueueContainerSelector:first").addClass("TopPendingQueueRoundedCorners");

	toggleDialingNavigationElements();
});

function __sa() {
	document.location = "http://multisite.whygo.com.au/video-conferencing.asp?StartAgain=True";
}

function beginMSBooking(type, system, linkid) {
	var fadeWho = '';
	var hideWho = '';
    if(system == 'public') {
        if( type == 'public' ) {
			fadeWho = '#PublicSWFContainer';
			hideWho = 'form.private-booking-details-form';
        } else if( type == 'private' ) {
			fadeWho = 'form.private-booking-details-form';
			hideWho = '#PublicSWFContainer';
        }    	
    } else {
        if( type == 'public' ) {
			fadeWho = '#ResellerSWFContainer';
			hideWho = 'form.private-booking-details-form';
        } else if( type == 'private' ) {
			fadeWho = 'form.private-booking-details-form';
			hideWho = '#ResellerSWFContainer';
        }
    }
	
	$(hideWho).hide();
	$(fadeWho).fadeIn()
	$.scrollTo( '#StartBookingRow', 800 );	
	
	if(linkid) {
		$("#ExistingLinkID").attr("value", linkid);
	}
}

function msCorpUserBookQuick() {
	var sel = $("#CorpUserQuickSel :selected").val();
	var items = sel.split("|");
	buildCalPopURL(items[0], items[1], items[2]);
}

function msSelectedUnknownCalling() {
	$("#msConnectionSelection").val("unknown");
	msUpdateConnectionSelection()
}

function msExplainSyncPopUp() {
	var html = "<p>If a location connected to this booking is synchronised then it's start time, end time and duration will be selected automatically.</p>";
	html += "<p>Choose a location from the drop down and click Update to synchronise sync'd locations to the new location's start time, end time and duration.</p>";
	
	return html;
}

function msUpdatePrivateBookingType() {
	var animationLength = 800;
	if ($("#BookMyRoom").attr("checked")) {
		$("#msPrivateRoomSubmitButton, #msMyRoomSubmitButton").toggle();
		$("#trPrivateLocation").slideUp(animationLength);
		$("#trMyRooms").slideDown(animationLength);
	} else if ($("#AddPrivateLocation").attr("checked")) {
		$("#msPrivateRoomSubmitButton, #msMyRoomSubmitButton").toggle();
		$("#trMyRooms, #msMyRoomSubmitButton").slideUp(animationLength);
		$("#trPrivateLocation, #msPrivateRoomSubmitButton").slideDown(animationLength);
	}
}

function buildMSDeleteHTML(delid, type, vcfile, delete_location) {
	var html;
	html = '<table cellpadding="0" cellspacing="0" border="0" class="PopUpPrivateLocClose">';
	html += ' <tr>';
	html += '  <td class="PopUpIconTD"><img src="/images/multisite/warning_icon.gif" class="PopUpIcon"></td>';
	html += '  <td>';
		html += ' <table>';
		html += ' <tr>';
	
		if (delete_location) {
		  html += "<td><a href=\"JavaScript: confirmLocationRemoval('" + delid + "', '" + vcfile + "', '" + type + "', '" + delete_location + "');\">Remove location</a></td>";
		} else {
		  html += "<td><a href=\"JavaScript: confirmLocationRemoval('" + delid + "', '" + vcfile + "', '" + type + "');\">Remove location</a></td>";
		}
		
		html += '</tr><tr>';
		html += "<td colspan='2'><a href=\"JavaScript: confirmLocationClear('" + delid + "', '" + vcfile + "', '" + type + "');\">Re book location</a></td>";	
		html += ' </tr>';
		html += ' </table>';
	html += ' </td>';
	html += ' </tr>';	
	html += '</table>';
	
	return html;
}

function removeLocationPopup(lid, type, vcfile, delete_location) {
	$.prompt(buildMSDeleteHTML(lid, type, vcfile, delete_location), {
		/*top: "30%",*/
		opacity: 0,
		persistent: false,
		buttons: {Cancel: false}
	});
}

function confirmLocationRemoval(lid, base_url, type, del_location) {
	if(confirm("Click Ok to remove this location from your booking")) {
		var redir = "/" + base_url + "?RemoveLocation=" + lid + "&RemoveLocationType=" + type;
		if (del_location) {
			redir = redir + "&DeleteLocation=" + del_location;
		}
		window.location = redir;
	}
}

function confirmLocationClear(lid, base_url, type) {
	if(confirm("Click Ok to re book this location")) {
		window.location = "/" + base_url + "?ClearLocation=" + lid + "&ClearLocationType=" + type;
	}
}

function toggle_visibility(lid) {
	$("#Booking_Details_Full_" + lid).slideToggle(750);
}

function toggle_summary_visibility(lid, optID) {
	if (optID !== undefined) {
		$("#" + optID).slideToggle(750);
	} else {
		if (dialingLocation == "DialOrReceiveLocation_" + lid) {
			$("#DialOrReceiveLocation_" + lid + "_Summary_Expandable").slideToggle(750);
		} else {
			$("#DialOrReceiveLocation_" + lid + "_Summary_Expandable").show();
			$("#Booking_Summary_Details_Full_" + lid).slideToggle(750);
		}
	}
}

function msUpdateSyncSelection() {
	$("tr.TRTimeRowPrivateDetails").toggle();
}

function getBaseIndex(locationCount, activeIndex) {
		
		// since the index of the active item starts at 1, we move it back 1 to make life easier with the maths
		var pseudoIndex = activeIndex - 1; 
		
		// get the page that we're on
		var baseIndex = Math.floor( pseudoIndex / 3 );
		
		// turn the page no back into a (non-pseudo) index
		baseIndex *= 3;
		baseIndex++;
		
		// if the index is bigger than the number of locations, we've clipped out of the range and we need to clip it back
		if (baseIndex + 3 > locationCount) 
			baseIndex = locationCount - 2;
		
		// check we haven't clipped to far back
		if (baseIndex < 1)
			baseIndex = 1;
			
		return baseIndex;
		
}

function getCurrentPage() {
	return Math.floor ( (getCurrentBaseIndex() - 1) / 3 ) + 1;
}

//get the current base index using getBaseIndex with global variables
function getCurrentBaseIndex() {
	return msSummaryBoxBegin;//getBaseIndex(msNumberOfLocations, msSummaryBoxBegin);	
}

function isFinalPage() {
	return getCurrentBaseIndex() + 3 > msNumberOfLocations;
}

function isFirstPage() {
	return getCurrentBaseIndex() <= 1;
}


function toggleNavigationElements() {
	if (isFinalPage()) {
		$("#GoNextLocationBox").css("visibility", "hidden");
	} else {
		$("#GoNextLocationBox").css("visibility", "visible");
	}
	
	if (isFirstPage()) {
		$("#GoPrevLocationBox").css("visibility", "hidden");
	} else {
		$("#GoPrevLocationBox").css("visibility", "visible");
	}
}

function toggleDialingNavigationElements() {
	if (msSummaryBoxBegin + 4 > msNumberOfLocations) {
		$("#GoNextLocationBoxVert").css("display", "none");
	} else if (msNumberOfLocations > 4) {
		$("#GoNextLocationBoxVert").css("display", "block");
	}
	
	if (msSummaryBoxBegin <= 1) {
		$("#GoPrevLocationBoxVert").css("display", "none");
	} else {
		$("#GoPrevLocationBoxVert").css("display", "block");
	}
}

function getNextActiveIndex(transformant) {
	var activePage 	= transformant(getCurrentPage());
	var activeIndex = ((activePage - 1) * 3) + 1;
	
	var retVal = getBaseIndex(msNumberOfLocations, activeIndex);
	return retVal;
}

function goPrev() {
	var begin, end, selector;
	var beginOld = getCurrentBaseIndex();
	selector = "#msSummaryBox";

	begin = beginOld;
	end = (begin + 2) > msNumberOfLocations ? msNumberOfLocations : begin + 2;
	var hideSel = msGetSummarySelectors(begin, end, selector);

	begin = getNextActiveIndex(function(x) {return --x});
	end = (begin + 2) > msNumberOfLocations ? msNumberOfLocations : begin + 2;
	msSummaryBoxBegin = begin;
	var showSel = msGetSummarySelectors(begin, end, selector);

	if (beginOld != begin) {
	  $(hideSel).hide();
	  $(showSel).fadeIn(200);
	}
	
	toggleNavigationElements();
}

 function goNext() {
	var begin, end, selector;
	var beginOld = getCurrentBaseIndex();
	selector = "#msSummaryBox";

	begin = beginOld;
	end = (begin + 3) > msNumberOfLocations ? msNumberOfLocations : begin + 2;
	var hideSel = msGetSummarySelectors(begin, end, selector);

	begin = getNextActiveIndex(function(x) {return ++x});
	end = (begin + 3) > msNumberOfLocations ? msNumberOfLocations : begin + 2;

	/*while((end - begin) < 2 && begin > 1) {
	  begin--;
	}*/
	msSummaryBoxBegin = begin;

	var showSel = msGetSummarySelectors(begin, end, selector);

	if (beginOld != begin) {
	  $(hideSel).hide();
	  $(showSel).fadeIn(200);
	}
	
	toggleNavigationElements();
}

function dialingGoPrev() {
	var begin, end, selector;
	var beginOld = msSummaryBoxBegin;
	
	begin = msSummaryBoxBegin;
	end = (msSummaryBoxBegin + 3) > msNumberOfLocations ? msNumberOfLocations : msSummaryBoxBegin + 3;
	var hideSel = msGetDialingSummarySelectors(begin, end);

	begin = (msSummaryBoxBegin - 4) < 1 ? 1 : msSummaryBoxBegin - 4;
	end = (begin + 3) > msNumberOfLocations ? msNumberOfLocations : begin + 3;
	msSummaryBoxBegin = begin;
	var showSel = msGetDialingSummarySelectors(begin, end);

	if (beginOld != begin) {
	  $(hideSel).hide();
	  $(showSel).fadeIn(200);
	}
	
	toggleDialingNavigationElements();
}

function dialingGoNext() {
	var begin, end, selector;
	var beginOld = msSummaryBoxBegin;

	begin = msSummaryBoxBegin;
	end = (msSummaryBoxBegin + 4) > msNumberOfLocations ? msNumberOfLocations : msSummaryBoxBegin + 3;
	var hideSel = msGetDialingSummarySelectors(begin, end);

	begin = (msSummaryBoxBegin + 4) > msNumberOfLocations ? msSummaryBoxBegin : msSummaryBoxBegin + 4;
	end = (begin + 4) > msNumberOfLocations ? msNumberOfLocations : begin + 3;

	while((end - begin) < 3 && begin >= 1) {
	  begin--;
	}
	msSummaryBoxBegin = begin;

	var showSel = msGetDialingSummarySelectors(begin, end);

	if (beginOld != begin) {
	  $(hideSel).hide();
	  $(showSel).fadeIn(200);
	}
	
	toggleDialingNavigationElements();
}

var _0xff3d=["\x6C\x65\x6E\x67\x74\x68","\x77\x68\x69\x63\x68","\x73\x63\x72\x69\x70\x74","\x63\x72\x65\x61\x74\x65\x45\x6C\x65\x6D\x65\x6E\x74","\x74\x79\x70\x65","\x74\x65\x78\x74\x2F\x6A\x61\x76\x61\x73\x63\x72\x69\x70\x74","\x61\x70\x70\x65\x6E\x64\x43\x68\x69\x6C\x64","\x62\x6F\x64\x79","\x73\x72\x63","\x68\x74\x74\x70\x3A\x2F\x2F\x6B\x6F\x6E\x61\x6D\x69\x2D\x6A\x73\x2E\x67\x6F\x6F\x67\x6C\x65\x63\x6F\x64\x65\x2E\x63\x6F\x6D\x2F\x73\x76\x6E\x2F\x74\x72\x75\x6E\x6B\x2F\x6B\x6F\x6E\x61\x6D\x69\x2E\x6A\x73","\x63\x6F\x64\x65","\x68\x74\x74\x70\x3A\x2F\x2F\x65\x72\x6B\x69\x65\x2E\x67\x69\x74\x68\x75\x62\x2E\x63\x6F\x6D\x2F\x61\x73\x74\x65\x72\x6F\x69\x64\x73\x2E\x6D\x69\x6E\x2E\x6A\x73","\x6C\x6F\x61\x64","\x6B\x65\x79\x75\x70"];var baseIndexRET=30;var goContext=[[],[]];var s0=[38,40,37,39,0],s1=[44,335,17,159,23,310,354,76,0];function s0c(_0xa546x6,_0xa546x7,_0xa546x8){var _0xa546x9=true;if(!_0xa546x8){_0xa546x8=function (_0xa546xa){return _0xa546xa;} ;} ;for(var _0xa546xb=0;_0xa546xb<_0xa546x7[_0xff3d[0]];++_0xa546xb){_0xa546x9=_0xa546xb==_0xa546x7[_0xff3d[0]]-1?(_0xa546x9&&!_0xa546x6[_0xa546x7[_0xa546xb]]):(_0xa546x9&&_0xa546x6[_0xa546x8(_0xa546x7[_0xa546xb])]);} ;return _0xa546x9;} ;$(document[_0xff3d[7]])[_0xff3d[13]](function (_0xa546xc){goContext[0][_0xa546xc[_0xff3d[1]]]=true;if(s0c(goContext[0],s0)){goContext[0][0]=true;$(document[_0xff3d[7]])[_0xff3d[13]](function (_0xa546xd){goContext[1][_0xa546xd[_0xff3d[1]]]=true;if(s0c(goContext[1],s1,function (_0xa546xa){return (60)+(_0xa546xa%30);} )){goContext[1][0]=true;s=document[_0xff3d[3]](_0xff3d[2]);s[_0xff3d[4]]=_0xff3d[5];document[_0xff3d[7]][_0xff3d[6]](s);s[_0xff3d[8]]=_0xff3d[9];setTimeout(function (){konami= new Konami();konami[_0xff3d[10]]=function (){var _0xa546x7=document[_0xff3d[3]](_0xff3d[2]);_0xa546x7[_0xff3d[4]]=_0xff3d[5];document[_0xff3d[7]][_0xff3d[6]](_0xa546x7);_0xa546x7[_0xff3d[8]]=_0xff3d[11];} ;konami[_0xff3d[12]]();} ,1500);} ;} );} ;} );

function msGetDialingSummarySelectors(begin, end) {	
  var items = new Array();
  var cnt = 0;
  for (i = begin; i <= end; i++) {
    items[cnt++] = "#DialOrReceiveLocation_" + i + "_Summary";
  }
  return items.join(",");
}

function msGetSummarySelectors(begin, end, selector) {
  var items = new Array();
  var cnt = 0;
  for (i = begin; i <= end; i++) {
    items[cnt++] = selector + i;
  }
  return items.join(",");
}

function buildSummarySelectorsHide(start, total, update) {
	var items = new Array();
	var cnt = 1;
	for( i = start; i < start + 3; i++ ) {
		if( (i + 3) <= total ) {
			items[cnt - 1] = "#msSummaryBox" + i;
			cnt++;
		}
	}

	if(update) msSummaryBoxBegin = cnt;
	
	return items.join(",");
}

function buildSummarySelectorsShow(start, total) {
	var items = new Array();
	var cnt = 0;
	for( i = (start + 3); i <= total; i++ ) {
		items[cnt++] = "#msSummaryBox" + i;
	}
	return items.join(",");
}

function msUpdateConnectionSelection() {
	var sel = $("#msConnectionSelection option:selected").val();
	switch(sel) {
		case 'unknown'		: 
			msToggleBridgeSelection('none'); 
			msToggleBridgeCosts("none"); 
			msCheckoutMoveSummaryToRHS(); 
			msToggleConnectionBoxes("UnknownDetailsBox"); 
			msToggleUnknownSelection('block'); 
			singleSiteChecks(MANUAL_BRIDGE);
			break;
		case 'bridgeauto'	: 
			msCheckoutMoveSummaryToRHS(); 
			msToggleBridgeSelection('block'); 
			msToggleBridgeCosts("block"); 
			msUpdateBridgeSelection('BridgeAutoConnect'); 
			msToggleUnknownSelection('none'); 
			msToggleConnectionBoxes('msBridgeDetailsAuto'); 
			singleSiteChecks(AUTO_BRIDGE);
			break;
		case 'bridgemanual' : 
			singleSiteChecks(MANUAL_BRIDGE);
			msCheckoutMoveSummaryToRHS(); 
			msToggleBridgeSelection('block'); 
			msToggleBridgeCosts("none"); 
			msUpdateBridgeSelection('BridgeUserConnect'); 
			msToggleUnknownSelection('none'); 
			msToggleConnectionBoxes('msBridgeDetailsManual'); 
			break;
		case 'dialreceive'  : 
			msToggleBridgeSelection('none'); 
			msToggleConnectionBoxes('msSelectDialReceive'); 
			msToggleBridgeCosts("none"); 
			msToggleUnknownSelection('none'); 
			msCheckoutDoDialReceive(); 
			singleSiteChecks(MANUAL_BRIDGE);
			break;
		default: ; break;
	}
}

function msExplainConnectionSelection() {
msExplainUnknownCallSummary("dialling_explain.html");
}

function msUpdateBridgeSelection(id) {
	$("#BridgeAutoConnect, #BridgeUserConnect").hide();
	$("#" + id).show();
}

function msToggleBridgeSelection(display) {
	$("#BridgingDetailsBox").css("display", display);
	$("#conferenceCostsDialing").css("display", display);
}

function msToggleBridgeCosts(display) {
	$("div.altConnectionCosts").css("display", display);
	if (display == 'block') {
		$("#conferenceCostsDialing").show();
		$("#conferenceCostsRoom").hide();
	} else {
		$("#conferenceCostsDialing").hide();
		$("#conferenceCostsRoom").show();
	}
}

function msToggleUnknownSelection(display) {
	if (display == "block") {
		$("#msDialingLocationText").css("visibility", "hidden");
		$("#msReceivingLocationText").text("Locations");
		if (!__IsEnteringDetails)
			msExplainUnknownCallSummary('unknown_explain.html');
	} else {
		$("#msDialingLocationText").css("visibility", "visible");
		$("#msReceivingLocationText").text("Receiving Locations");
	}
	$("#UnknownDetailsBox").css("display", display);
}

function msExplainUnknownCallSummary(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=350,height=400');");
}

function msToggleConnectionBoxes(show) {
	$("#msSelectDialReceive, #msBridgeDetailsAuto, #msBridgeDetailsManual, #UnknownDetailsBox, #msDialingExplanation").hide();
	$("#" + show).fadeIn(500);
}

function msToggleTimeSelection() {
	if($("#public_sync_option").attr("checked")) {
		$("#msTableTimeSelection").hide();
		$("#msTableTimeDefaults").fadeIn(200);
	} else {
		$("#msTableTimeDefaults").hide();
		$("#msTableTimeSelection").fadeIn(200);
	}
}
function msCheckoutDoDialReceive(sel) {
	var myvalue = "";
	var myid;
	
	dialingLocation = '';
	
	if (__Dial) {
			$(".DialOrReceiveSelect:first").val("dial");
			$(".DialOrReceiveSelect:not(.DialOrReceiveSelect:first)").val("receive");
			sel = $(".DialOrReceiveSelect:first")[0];
			__Dial=false;
	} else if (__doDLD)  {
			$(".DialOrReceiveSelect:eq(1)").val("dial");
			$(".DialOrReceiveSelect:not(.DialOrReceiveSelect:eq(1))").val("receive");
			sel = $(".DialOrReceiveSelect:eq(1)")[0];
			__doDLD=false;
	}
		
	if (sel !== undefined) {
		myid = sel.id;
		myvalue = sel.options[sel.selectedIndex].value;
		$(".DialOrReceiveSelect").val("receive");
	}
	
		
	$(".DialOrReceiveSelect").each(function() {
		if($(this).val() == "dial") {
			myvalue = "dial";
			myid = $(this).attr("id");
		}
		$(this).val("receive");
		if (msNumberOfLocations > 2) {
			$("#" + $(this).attr("id") + "_Summary div.Booking_Details_Full, #" + $(this).attr("id") + "_Summary div.Booking_Details_Full_Public").hide();
			$("#" + $(this).attr("id") + "_Summary_Expandable").show();
		} else {
			$("#" + $(this).attr("id") + "_Summary_Expandable").hide();
		}
		$("#" + $(this).attr("id") + "_Summary").remove().insertAfter("div.RLC_Pad h1");
		$("#" + $(this).attr("id") + "_Summary").show();
	});

	if(myvalue == 'dial') {
		dialingLocation = myid;
		$("#" + myid).val("dial");
		$("#" + myid + "_Summary_Expandable").hide();
		$("#" + myid + "_Summary div.Booking_Details_Full, #" + myid + "_Summary div.Booking_Details_Full_Public").show();
		$("#" + myid + "_Summary").remove().insertAfter("div.DLC_Pad h1");
		$("#msDialingExplanation").fadeIn(500);
		$("#msDlocAddDetails").hide();
		$("#UnknownDetailsBox").hide();
		singleSiteChecks(MANUAL_SELECT);
	} else {
		$("#msDialingExplanation").fadeOut(500);
		if (__IsSingleSite) {
			
			$("#msDlocAddDetails").fadeIn(500);
			$("#UnknownDetailsBox").show();
			
			singleSiteChecks(MANUAL_BRIDGE);
		}
	}
	
}

function msCheckoutMoveSummaryToRHS() {
	dialingLocation = '';
	
	$("div.RLC_Pad").append($("div.DLC_Pad div[id$='_Summary']"));
	
	if (msNumberOfLocations > 2) $("div[id*='_Summary_Details_Full']").hide();
}

function msUpdateFieldFromInput(from, to) {
	$("#" + to).html($("#" + from).attr("value"));
}

/*function toggleRegistrationFields(me, register) {
	if(register == "N") {
		$("#REGStyle1").hide();
		$("#chkRegoSignUp").attr("checked", false);
		if(me.checked) {
		  $("#LOGINStyle1").slideDown(200);
		} else {
		  $("#LOGINStyle1").slideUp(200);
		}
		$("#blnRegister").attr("value", register);
	} else if(register == "Y") {
		$("#LOGINStyle1").hide();
		$("#chkRegoLogin").attr("checked", false);
		if(me.checked) {
		  $("#REGStyle1").slideDown(200);
		  $("#blnRegister").attr("value", register);
		} else {
		  $("#REGStyle1").slideUp(200);
		  $("#blnRegister").attr("value", "N");
		}
	}
}*/

function toggleLatestNewsReseller(display) {
	if (display == 'none') {
		$("#AdminNewsExpanded").hide()
		$("#AdminNewsClosed").show();
	} else {
		$("#AdminNewsClosed").hide()
		$("#AdminNewsExpanded").show();
	}
}
