/*
 * Javascript used in showyp.jsp
 */

/**
 * Toggle visibility of long description in summary tab.
 */
function showLongDescription (btnEl) {
	var ldEl = document.getElementById('long_description');
	ldEl.style.height = "auto";
	ldEl.style.visibility="visible";
	btnEl.disabled=true;
}
function toggleBablefishVisibility() {
	var flagsEl = document.getElementById("translateFlags");
	var el = document.getElementById("bablefish");
	if (el.style.visibility == "visible") {
		el.style.visibility='hidden';
		el.style.height='0px';
		//flagsEl.style.height='42px';
	} else {
		el.style.visibility='visible';
		el.style.height='153px';
		flagsEl.style.opacity='0.2';
	}
}

 
function toggleRatingPaneVisibility() {
	var rp = document.getElementById("ratingPane")
	if (rp.style.display == 'none') {
		rp.style.display='';
	} else {
		rp.style.display='none';
	}
}

/*
 * Update map to show nearby records. If 'classification' missing all 
 * records will be shown
 */
function showNearby (map, ypId,classification) {
	var qurl = "/GalwayNet/jsp/yp/query-nearby.jsp?id=" + ypId;
	if (classification) {
		qurl += "&c=" + classification;
	}
	var metersPerPixel = map.getUnitsPerPixel().kilometers * 1000;
	var outerRadius = map.getOuterRadius() * metersPerPixel;
	qurl += "&r=" + parseInt(outerRadius);
	var request = YAHOO.util.Connect.asyncRequest('GET', qurl, 
		{ success:mapUpdateSuccessHandler, failure:mapUpdateFailureHandler });
}

/*
 * Handles map update. Requires map and centerPoint global variables
 */
function mapUpdateSuccessHandler(o) {

	// Eval JSON (from trusted source)
	var myObject = eval( '(' + o.responseText + ')' );
	
	// Was anything found? Popup alert if not.
	if (myObject.items.length-1 == 0) {
		alert ('Nothing found within radius of ' + myObject.searchRadius + 'm');
		return;
	}
	
	//alert ('Found ' + (myObject.items.length-1) + 'items in' + myObject.searchRadius + 'm');
	
	var pointArray = {};
	map.removeMarkersAll();
	
	// Ignore last item (just a dummy entry)
	for (var i = 0; i < myObject.items.length-1; i++) {
		var item = myObject.items[i];
		var markerPoint = new YGeoPoint(item.lat,item.lon);
		pointArray[i] = new YGeoPoint(item.lat,item.lon);
		//alert ('Adding ' + pointArray[i].Lat + ',' + pointArray[i].Lon + ' to point array at ' + i);
		var bubbleText = "<div class=\"bubbleDiv\"><h3><a href=\"showyp.shtml?id=" + item.id + "\">" + item.name + "</a></h3></div>";
    	var marker = createMarker(markerPoint, i, bubbleText, "blue");
		map.addOverlay(marker);
	}
	
	
	
	// Redraw center marker	
	var marker = createMarker(centerPoint, 1, "x", "red");
	map.addOverlay(marker);
	
	// Add center point and get optimum zoom level
	pointArray[i] = centerPoint;
	// This appears not to work!
	//var bestZoom = map.getBestZoomAndCenter(pointArray);
	//var bestZoom = map.getZoomLevel(pointArray);
	//map.setZoomLevel(bestZoom);
	
}

/*
 *
 * This is a simple failure handler that will display
 * the HTTP status code and status message if the resource
 * returns a non-2xx code.
 *
 */
function mapUpdateFailureHandler(o){
	alert ('error:' +  o.status + " " + o.statusText);
}

function createMarker(geopoint, num, swtext, color) { 
    var myImage = new YImage();  
    myImage.src = '/GalwayNet/assets/markers/marker-' + color + '.png';
    myImage.size = new YSize(8,8); 
    myImage.offsetSmartWindow = new YCoordPoint(4,4); 
    var marker = new YMarker(geopoint,myImage); 
    marker.setSmartWindowColor("blue");
    //var label = "<img src=http://us.i1.yimg.com/us.yimg.com/i/us/ls/gr/" + num + ".gif>"; 
    //marker.addLabel(label); 
    YEvent.Capture(marker,EventsList.MouseClick, function() { marker.openSmartWindow(swtext) }); 
    return marker; 
} 

function ratingsPopup(ypid) {
		var url = '/GalwayNet/jsp/yp/yprate.jsp?id=' + ypid;
		var winName = 'yprate-win-' + ypid;
		eval("ratingsPopupWindow = window.open(url, winName, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=640,height=480');");
}
	

function initYMap (map, centerPoint, zoomLevel) {

	// Add controls
	map.addPanControl(); 
	map.addZoomLong(); 
	map.addTypeControl();

	map.removeMarkersAll();
	map.drawZoomAndCenter(centerPoint, zoomLevel);

	map.setMapType(YAHOO_MAP_REG);

	//Get valid map types, returns array [YAHOO_MAP_REG, YAHOO_MAP_SAT, YAHOO_MAP_HYB]
	var myMapTypes = map.getMapTypes(); 
	//var marker = new YMarker(centerPoint);
	var marker = createMarker(centerPoint, 1, "", "red");
	//marker.addLabel("X");
	map.addOverlay(marker);
}


/* Toggle between active icon and inactive icon */
function toggleRatingIcon(iconImage, ypId) {

	// Set all other options to inactive
	imgid = iconImage.id.substring(0,iconImage.id.length-2);
	for (i = 0; i < 5; i++) {
		var el = document.getElementById(imgid + "_" + i);
		if (el != iconImage && isRatingIconActive(el)) {
			setRatingIcon(el,false);
		}
	}
	
	// toggle active | inactive
	setRatingIcon(iconImage, ! isRatingIconActive(iconImage));
	
	var categoryId = iconImage.id.substring(3,iconImage.id.length-2);
	if (isRatingIconActive(iconImage)) {
		var score = iconImage.id.substring(iconImage.id.length-1,iconImage.id.length);
		sendRating(ypId, categoryId, score);
	} else {
		sendRating(ypId, categoryId, -1); // delete rating
	}
		
}
function setRatingIcon (iconImage, active) {
	var s = iconImage.src.substring(0,iconImage.src.length-5);
	if (active) {
		iconImage.src = s + "a.png";
	} else {
		iconImage.src = s + "i.png";
	}
}
function isRatingIconActive (iconImage) {
	return (iconImage.src.indexOf("a.png") > 0)
}
function requestValidationCode () {
	var emailAddress = document.getElementById('emailAddress').value;
	if (!emailAddress || emailAddress.length==0) {
		alert ('Email address is required.');
		document.getElementById('emailAddress').style.border="2px solid red;";
		return false;
	}
	//document.getElementById('emailAddress').style.border="";
	
	var url = "/GalwayNet/jsp/yp/yprate-ajax-requestvc.jsp?email=" 
		+ escape(emailAddress)
		+ "&comment=" 
		+ escape(document.getElementById('f_comment'));
	var request = YAHOO.util.Connect.asyncRequest('GET', url, 
		{ success:generalSuccessHandler, failure:generalFailureHandler });
	document.getElementById('emailPane').style.visibility='hidden';
	document.getElementById('vcPane').style.visibility='visible';
	return false;
}

function submitValidationCode () {
	var vc = document.getElementById('vc').value;
	if (!vc || vc.length==0) {
		alert ('Validation code required (4 digit number). Check your email.');
		document.getElementById('vc').style.border="2px solid red;";
		return false;
	}
	//document.getElementById('vc').style.border="";
	
	var url = "/GalwayNet/jsp/yp/yprate-ajax-submitvc.jsp?vc=" + vc;
	var request = YAHOO.util.Connect.asyncRequest('GET', url, 
		{ success:submitVcSuccessHandler, failure:generalFailureHandler });
	return false;
}

function submitVcSuccessHandler(o) {
	// Eval JSON (from trusted source)
	var response = eval('(' + o.responseText + ')');
	var vcStatusEl = document.getElementById('vcStatus');
	var vcPaneEl = document.getElementById('vcPane');
	if (response.status == 'OK') {
		//vcPaneEl.innerHTML="SUCCESS";
		vcPaneEl.className="vcSuccess";
		vcPaneEl.innerHTML=response.statusText;
	} else {
		vcStatusEl.innerHTML="<b>WRONG CODE: Check your email and try again.</b>";
		vcStatusEl.className="vcError";
	}	
}

/*
 * Send individual score to server in background 
 */
function sendRating (ypId,categoryId,score) {
	var url = "/GalwayNet/jsp/yp/yprate-ajax-submit.jsp?ypid=" + ypId
	 + "&cid=" + categoryId + "&s=" + score;
	var request = YAHOO.util.Connect.asyncRequest('GET', url, 
		{ success:generalSuccessHandler, failure:generalFailureHandler });
}


function generalSuccessHandler(o) {
}
function generalFailureHandler(o){
	alert ('unexpected error from server:' +  o.status + " " + o.statusText);
}

function checkMobileNumber () {
	var f = document.getElementById('field_mobile_number');
	if (f.value.length != 7) {
		alert ('Mobile numbers must be 7 digits in length.');
		return false;
	}
	return true;
}
function selectTab (tabView, tabName) {
	var tabs = tabView.get('tabs'); 
	for (var i = 0; i < tabs.length; i++) { 
		if (tabs[i].get('href') == '#' + tabName) { 
			tabView.set('activeIndex', i); 
			break;
		} 
	}
}
