/*
uses jQuery
*/

/* SITE DEPENDANT */
//var model_base_url = "http://joby.passthepeas.net/products/gorillapod/findmygpod2/models.php?make="; 
//var model_base_url = window.location.protocol+"//"+window.location.hostname+"/products/gorillapod/findmygpod2/m.php?make="; 


var model_base_url = "/api/fmg/m?make="; 

// returns information for a specific model
// used on store page
// !!!!!!!!!!!! currently not used
function displayModel(comprehensive) {	
	// clear any existing recommendations
	clearModel();
	
	// check the model field for recommended_to_web_abbr
	var make_name = $('select[name="make"]').val();
	var model_name = $('select[name="model"]').val();
	var recommended_gpods = $('option[value="'+model_name+'"]').data('gpods'); 
	var gpodinfo = $('select[name="model"]').data('gpodinfo');
	
	var recommended_text = "";
	
	$(recommended_gpods).each(function(i){
		// look up info based on this == 'gp1' etc
		var short = gpodinfo[this]['short'];
		var product_name = gpodinfo[this]['title']; 
		
		line = "Recommended for "+make_name+' '+model_name;
		
		// create recommendation divs and add them after the appropriate #anchor
		var gpod_anchor = $('a[name="'+short+'"]');
		
		$('<div class="recommended_gpod">'+line+'</div>').appendTo(gpod_anchor);
		// add .recommendedStoreGroup to parent .storeGroup
		gpod_anchor.closest('.storeGroup').addClass('recommendedStoreGroup');
		
		// highlight the appropriate gpods up in the lineup
		$('.gpodLineup .'+short).addClass('recommendedGpodLineup');
		
		// XXXXXXXXget product names from DOM
		//var name = gpod_anchor.siblings('div.title').children('h2').text();
		if (i > 0) {
			recommended_text = recommended_text + ' or the ';
		}
		var alink = "#" + short;
		// if there are no anchors to go to, then link to product page instead
		if (gpod_anchor.length == 0) {
			alink = gpodinfo[this]['link'];	
		}
		recommended_text = recommended_text + '<a href=' + alink + '">' + product_name + '</a>';
	}); 
	// create new .choseGpod
	$('<div class="choseGpod"></div>').append($('<div class="gpodRecommendation">For the <b>'+make_name+' '+model_name+'</b> we recommend the '+recommended_text+'</div>')).append($('<a href="#">Look up another camera</a>').click(function(){clearModel();return false}).wrap('<div class="fmg_small">')).insertAfter('.chooseGpod');
	$('.chooseGpod').hide();
}

// resets the recommendation
// used on store page
function clearModel() {
	$('div.recommended_gpod').remove();
	$('.recommendedStoreGroup').removeClass('recommendedStoreGroup');
	$('.recommendedGpodLineup').removeClass('recommendedGpodLineup');
	$('.choseGpod').remove();
	$('.chooseGpod').show();
}

function recommendedGpods(fmgDiv) {
	ret = $(fmgDiv).find('select[name=model] option[value="'+modelField.val()+'"]').data('gpods'); 
	//console.log(ret);
	return ret;
}

function cameraName(fmgDiv) {
	makeField = $(fmgDiv).find("select[name=make]");
	modelField = $(fmgDiv).find("select[name=model]");
	return makeField.val() + ' ' + modelField.val();
}

// returns recommendation text based on given fmg div.
// gets strings from the data in fmgDiv
// url:  determines which link is displayed, either "store_url" or "info_url"
function recommendationText(fmgDiv, currentGpod, url) {
	if (currentGpod == 'gpm') currentGpod = 'gp1';

	if (typeof(url) == 'undefined') {
		url = 'store_url';
	}
	
	makeField = $(fmgDiv).find("select[name=make]");
	modelField = $(fmgDiv).find("select[name=model]");
	recommended_gpods = recommendedGpods(fmgDiv); 
	
	var str = '';
	// see if we're displaying a single recommendation or many	
	if (recommended_gpods.length > 1) {
		// figure out which one is which
		if (recommended_gpods[0] == 'gp1' || recommended_gpods[0] == 'gm1') { 
			// display the 'similar_gpod'
			str = $(fmgDiv).data('similar_gpod');
			gp1 = gpodTitle('gp1', currentGpod, fmgDiv, url);
			gm1 = gpodTitle('gm1', currentGpod, fmgDiv, url);
			gpm = gpodTitle('gpm', currentGpod, fmgDiv, url);
			str = str.replace("<span class='gp1'>", "<span class='gp1'>" + gp1);
			str = str.replace("<span class='gm1'>", "<span class='gm1'>" + gm1);
			str = str.replace("<span class='gpm'>", "<span class='gpm'>" + gpm);
		} else {
			// display the 'double_gpod'
			str = $(fmgDiv).data('double_gpod');
			stronger = lighter = '';
			if (recommended_gpods[0] == 'gp8' || recommended_gpods[1] == 'gp2') {
				// then we know that 0 is the larger
				stronger = gpodTitle(recommended_gpods[0], currentGpod, fmgDiv, url);
				lighter = gpodTitle(recommended_gpods[1], currentGpod, fmgDiv, url);
			} else {
				stronger = gpodTitle(recommended_gpods[1], currentGpod, fmgDiv, url);
				lighter = gpodTitle(recommended_gpods[0], currentGpod, fmgDiv, url);		
			}
			
			str = str.replace("<span class='stronger_gpod'>", "<span class='stronger_gpod'>" + stronger);
			str = str.replace("<span class='lighter_gpod'>", "<span class='lighter_gpod'>" + lighter);
		}
	} else {
		if (currentGpod) {
			// display the 'e_gpod'
			if ($(recommended_gpods).index(currentGpod) != -1) {
				// then this is one of the recommended
				str = $(fmgDiv).data('right_gpod');
			} else {
				// not the recommended
				str = $(fmgDiv).data('wrong_gpod');
			}
		} else {
			// not the recommended
			str = $(fmgDiv).data('single_gpod');
		}
		gpod = gpodTitle(recommended_gpods[0], currentGpod, fmgDiv, url);
		str = str.replace("<span class='gpod'>", "<span class='gpod'>" + gpod);
		
	}
	
	// replace camera string
	camera = makeField.val() + ' ' + modelField.val();
	str = str.replace("<span class='camera'>", "<span class='camera'>" + camera);
	
	return str;
}

// displays gpod title, with link if not current
function gpodTitle(rec_gpod, cur_gpod, fmgDiv, url) {
	if (typeof(url) == 'undefined') {
		url = 'store_url';
	}
	
	gpodinfo = $(fmgDiv).data('gpodinfo');
	if (typeof(gpodinfo[rec_gpod]) != 'object') {
		return '';
	} else if (rec_gpod == cur_gpod) {
		// then don't display a link
		
		// but add a comment
		str = $(fmgDiv).data('current_gpod');
		return gpodinfo[rec_gpod]['title'] + ' ' + str;
	}
	return gpodinfo[rec_gpod][url] + gpodinfo[rec_gpod]['title'] + '</a>';
}

// used on both store page and admin backend
function setUpFmg(parentDiv, api_url) {
	makeField = $(parentDiv).find("select[name=make]");
	modelField = $(parentDiv).find("select[name=model]");
	
	// attach listener to the make select
	$(makeField).change(function(){
		//empty of old models
		$(modelField).empty(); 
		if (typeof(api_url) == 'undefined') {
			api_url = model_base_url;
		}
		var json_url = api_url + $(this).val() + '&info=yes&callback=?'; 
		
		// fill with new models from json
		$.getJSON(json_url,
			function(json){
				// if the json request has models and not just makes..
				if (json.models) {
					$.each(json.models, function(i,item){
						$("<option value='"+item.name+"'>"+item.name+"</option>").data('gpods',item.rec_gpods).appendTo(modelField);
					}); 
					//$('.fmg').data('gpodinfo',json.info); 
					$(parentDiv).data('gpodinfo',json.info); 
				}
        });		
		
		parentDiv = $(modelField).closest('.fmg');
		
		// if has class "include_blank", include a blank spot
		if ($(modelField).hasClass("include_blank")) {  
			if ($(makeField).val() != '') {
				$("<option value=''>"+parentDiv.data('choose_make')+"</option><option disabled='disabled'>------</option>").prependTo(modelField);
			} else {
				$("<option disabled='disabled'>"+parentDiv.data('choose_make')+"...</option>").appendTo(modelField);
			}
		}
	});
}

// used on admin backend
/**************************************************************/
function displayModelList(tr, event) {
	$("#modelList").remove();
	// create and position the modellist
	$(document.body).append("<div id='modelList'></div>");
	//$("#modelList").css('left',event.pageX);
	$("#modelList").css('left',15/*event.pageX-300*/); 
	$("#modelList").css('top',event.pageY+15);
	// create and add close button
	$("<a href='#' class='close button'>Close</a>").click(function() {
		$("#modelList").remove();
		return false;
	}).appendTo("#modelList");
	$("<div class='list'></div>").appendTo("#modelList");
	// find the make field
	var make_select = tr.children('td').children("[name^='make']"); 
	var make = make_select.val();
	// display old model name at top
	var old_model = tr.children('td.model').children("input[name^='model']:first").val(); 
	//$("<h3>"+make+" "+old_model+"</h3>").appendTo('#modelList');
	// get models based on make
	var json_url = model_base_url+make+'&info=yes&verbose=yes&callback=?';
	
	// take the numerical part of the existing name and see if we can do some matching
	
	// first see if there are any like "60W"
	// var number_component = old_model.match(/\w*\d+\w*/);
	var number_component = old_model.match(/\d+/);
	if (number_component == null) {
		// then try the last word
		number_component = old_model.match(/\w+$/);
	}
	// flag "i" for RegExp allows for case insensitivity
	var number_re = new RegExp("(" + number_component + ")", "i");
	$.getJSON(json_url,
		function(json){   
			$.each(json.models, function(i,item){
				// only show weight if not 0
				weight = '';
				if (item.weight > 0) {
					weight = " <span class='weight'>"+item.weight+"g</span>";
				}
				var search_results = item.name.match(number_re);
				var display_name = item.name.replace(number_re, '<b>$1</b>');
				
				var search_match = '';
				if (search_results != null) {
					search_match = "class='match'";
				}
				$("<a href='' "+search_match+">"+display_name+weight+"</a>").click(function() {
					setExistingModel(tr, item, make);
					$("#modelList").remove();
					return false;
				}).appendTo("#modelList div.list");  
			});
        });
}

/*
sets m_id, which points to existing camera model. displays different row and hides original. options to undo or copy values
jQuery tr - <tr> to hide and replace
jQuery model - model object retrieved from json
String make - string with make name, used for display
*/
function setExistingModel(tr, model, make) { 
	// set hidden m_id 
	var model_id_hidden = tr.children('td.id').children("input[name^='m_id']");
	model_id_hidden.val(model.id); 
	// set up visuals
	var tr_id = tr.children('td.id').text();
	var ripeness = tr.children('td.ripeness').text();
	var old_model = tr.children('td.model').children("input[name^='model']:first").val(); 
	var new_tr = "<tr class='existing'><td class='id'>"+tr_id+"</td><td class='skip'></td><td class='make'>"+make+"</td><td colspan='5' class='model'>"+model.name+" (was &ldquo;"+old_model+"&rdquo;) </td><td class='email'></td><td class='ripeness'>"+ripeness+"</td></tr>";
	new_tr = $(new_tr).insertAfter(tr);
	// detach and move over the email
	var email = tr.children('td.email').children("input[name^='email']");
	new_tr.children('td.email').append(email);
	// attach an undo button
	var undo_link = "<a href='#' class='button'>Undo</a>";
	var copyback_link = "<a href='#' class='button'>Copy Attributes</a>";
	var middle_td = new_tr.children('td.model'); 
	middle_td.append($(undo_link).click(function(){
		undoExistingModel(new_tr, tr, model, false);
		return false;
	}));
	middle_td.append($(copyback_link).click(function(){
		undoExistingModel(new_tr, tr, model, true);
		return false;
	}));
	// hide the tr
	tr.hide();
}

function undoExistingModel(new_tr, tr, model, copyBack) {
	// move back the mail 
	var email = new_tr.children('td.email').children("input[name^='email']");
	tr.children('td.email').append(email);
	// remove the new_tr
	new_tr.remove();
	// show the tr
	tr.show();
	// unset the n_id
	var model_id_hidden = tr.children('td.id').children("input[name^='m_id']");
	model_id_hidden.val('');
	// copy stats if applicable
	if (copyBack) {
		var weight = tr.children('td.weight').children("input[name^='weight']:first");
		var slr = tr.children('td.slr').children("input[name^='slr']:first");
		var adapter = tr.children('td.apater').children("input[name^='adapter']:first");
		var recommended = tr.children('td.recommended').children("select[name^='recommended']:first");
		weight.val(model.weight);
		slr.each(function(){ this.checked = (model.slr == '1') ? true : false });
		adapter.each(function(){ this.checked = (model.adapter == '1') ? true : false }); 
		recommended.val(model.rec_code);  
	}
} 
