/**************************************************************************************************************************************/
/** lightbox popup **/
function Redirect(ref, scr) {
	jQuery.post("/user.php", { 
			login: 1,
			ref: ref,
			scr: scr
		},
		function(data) {
			if(data.log == '1') {
				if(data.scr != '') {
					document.location.href = 'javascript: ' + data.scr;
				} else if(data.ref != '') {
					document.location.href = data.ref;
				}
			} else {
				//open login box with re and scr added to the url
				var href = jQuery('#login_link').attr("href");
				href = href + "&ret=" + data.ref + "&scr=" + data.scr;
				jQuery('#login_link').attr("href", href);
				jQuery('#login_link').trigger('click');
			}
		}
	, "json");
}

/**************************************************************************************************************************************/
/** front banner slideshow **/
function slideSwitch() {
	var $active = jQuery('#slideshow DIV.active');
	
	if ( $active.length == 0 ) $active = jQuery('#slideshow DIV:last');

	// use this to pull the divs in the order they appear in the markup
	var $next =  $active.next().length ? $active.next()
		: jQuery('#slideshow DIV:first');

	// uncomment below to pull the divs randomly
	// var $sibs  = $active.siblings();
	// var rndNum = Math.floor(Math.random() * $sibs.length );
	// var $next  = $( $sibs[ rndNum ] );


	$active.addClass('last-active');

	$next.css({opacity: 0.0})
		.addClass('active')
		.animate({opacity: 1.0}, 1000, function() {
			$active.removeClass('active last-active');
		});
}

jQuery(function() {
	setInterval( "slideSwitch()", 5000 );
});

/**************************************************************************************************************************************/
/** licence calculator **/

function LicenseCalculator(next_select_id, step,  value) {
	jQuery.get("/single-image.html", { 
			login: 1,
			ajax: 1,
			next_select_id: next_select_id,
			selected_licr_id: value,
			step: step
		},
		function(xml) {
			Clear_License_Fields(next_select_id);
			
			if(next_select_id == 'licr_duration') {
				document.getElementById('licr_start_license_day_check').innerHTML = "<img src='/_d/buttons/btn_lightbox_add.gif'/>";
				document.getElementById('licr_start_license_day').disabled = false;
				document.getElementById('licr_start_license_month').disabled = false;
				document.getElementById('licr_start_license_year').disabled = false;
			}
						
			var select_id = document.getElementById(next_select_id);
			select_id.disabled = false;
			select_id.options.length = 0;
			jQuery(xml).find(next_select_id).each(function()
			{
				jQuery(this).find("option").each(function()
				{
				  select_id.options[select_id.options.length] = new Option(jQuery(this).text(), jQuery(this).attr("value"));
				  var  current = select_id.options.length - 1;
				  select_id.options[current].id = jQuery(this).attr("id");
				});
			});
			Update_License_Cost();
		}
	, "xml");	
}

function ActivateButton(value) {
		if(value != 0) {
			document.getElementById('submitBtn').disabled = false;
			document.getElementById('submitBtn').className = 'btn_large fright';
		} else {
			document.getElementById('submitBtn').disabled = true;
			document.getElementById('submitBtn').className = 'btn_large_inactive fright';
		}
}

function Clear_License_Fields(next_select_id) {
	switch(next_select_id) {
		case 'licr_usage':

		case 'licr_circulation':
			licr_circulation_select = document.getElementById('licr_circulation');
			licr_circulation_select.options.length = 0;
			licr_circulation_select.options[0] = new Option('-- Please select an appriopriate value', 0);
			licr_circulation_select.options[0].id = 1;
			document.getElementById('licr_circulation').disabled = true;
			document.getElementById('licr_circulation_check').innerHTML = "<img src='/_d/0.gif' width='20'/>";
			
		case 'licr_countries':
			licr_countries_select = document.getElementById('licr_countries');
			document.getElementById('licr_countries_check').innerHTML = "<img src='/_d/0.gif' width='20'/>";
			licr_countries_select.options.length = 0;
			licr_countries_select.options[0] = new Option('-- Please select an appriopriate value', 0);
			licr_countries_select.options[0].id = 1;
			document.getElementById('licr_countries').disabled = true;
			document.getElementById('licr_start_license_day').disabled = true;
			document.getElementById('licr_start_license_month').disabled = true;
			document.getElementById('licr_start_license_year').disabled = true;
			document.getElementById('licr_start_license_day_check').innerHTML = "<img src='/_d/0.gif' width='20'/>";
			
		case 'licr_duration':
			licr_duration_select = document.getElementById('licr_duration');
			licr_duration_select.options.length = 0;
			licr_duration_select.options[0] = new Option('-- Please select an appriopriate value', 0);
			licr_duration_select.options[0].id = 1;
			document.getElementById('licr_duration').disabled = true;
			document.getElementById('licr_duration_check').innerHTML = "<img src='/_d/0.gif' width='20'/>";
			
		case 'licr_industry':
			licr_industry_select = document.getElementById('licr_industry');
			licr_industry_select.options.length = 0;
			licr_industry_select.options[0] = new Option('-- Please select an appriopriate value', 0);
			licr_industry_select.options[0].id = 1;
			document.getElementById('licr_industry').disabled = true;
			document.getElementById('licr_industry_check').innerHTML = "<img src='/_d/0.gif' width='20'/>";
	}
	//license button
	document.getElementById('submitBtn').disabled = true;
	document.getElementById('submitBtn').className = 'btn_large_inactive fright';
}

function Update_License_Cost() {
	var based_price = 63;
	var model = 1;
	var usage = 1;
	var circulation = 1;
	var countries = 1;
	var duration = 1;
	var industry = 1;
	
	var model_select = document.getElementById('licr_model');
	for (var i = 0; i < model_select.options.length; i++){
		 if(model_select.options[i].selected == true){
			 model = model_select.options[i].id;
			 break;
		 }
	}
	
	var usage_select = document.getElementById('licr_usage');
	for (var i = 0; i < usage_select.options.length; i++){
		 if(usage_select.options[i].selected == true){
			 usage = usage_select.options[i].id;
			 break;
		 }
	}
	
	var circulation_select = document.getElementById('licr_circulation');
	for (var i = 0; i < circulation_select.options.length; i++){
		  if(circulation_select.options[i].selected == true){
			 circulation = circulation_select.options[i].id;
			 break;
		 }
	}
	
	var countries_select = document.getElementById('licr_countries');
	for (var i = 0; i < countries_select.options.length; i++){
		 if(countries_select.options[i].selected == true){
			 countries = countries_select.options[i].id;
			 break;
		 }
	}
	
	var duration_select = document.getElementById('licr_duration');
	for (var i = 0; i < duration_select.options.length; i++){
		 if(duration_select.options[i].selected == true){
			 duration = duration_select.options[i].id;
			 break;
		 }
	}
	
	var industry_select = document.getElementById('licr_industry');
	for (var i = 0; i < industry_select.options.length; i++){
		 if(industry_select.options[i].selected == true){
			 industry = industry_select.options[i].id;
			 break;
		 }
	}
	
	var total = based_price*model*usage*circulation*countries*duration*industry;
	document.getElementById('total_license_cost').value = formatCurrency(total);
	
	Licence_Preview();	
}

function formatCurrency(num){
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for ( i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function Licence_Preview() {
	if(document.getElementById('licr_start_license_day').disabled == false) { 
		var date_day = document.getElementById('licr_start_license_day').value;
		var date_month = document.getElementById('licr_start_license_month').value;
		var date_year = document.getElementById('licr_start_license_year').value;
	} else {
		var date_day = 0;
		var date_month = 0;
		var date_year = 0;
	}
	
	jQuery.get("/single-image.html", { 
			login: 1,
			ajax: 1,
			step: 'preview',
			licr_model: document.getElementById('licr_model').value ,
			licr_usage: document.getElementById('licr_usage').value,
			licr_circulation: document.getElementById('licr_circulation').value,
			licr_countries: document.getElementById('licr_countries').value,
			licr_start_license_day: date_day,
			licr_start_license_month: date_month,
			licr_start_license_year: date_year,
			licr_duration: document.getElementById('licr_duration').value,
			licr_industry: document.getElementById('licr_industry').value
		},
		function(responseText) {
			var doc = document.getElementById('license_receipt');
			doc.value = responseText;
		}			
	, "html");	
}

function Manage_Free_Download(horizontal, img_id) {
	jQuery.post("/user.php", { 
		ajax: 1,
		send: 1
	},
	function(responseText) {
		document.location.href='/download_FreeRM_'+horizontal+'_'+img_id+'.zip';
	}
	, "html");
	
	/*advAJAX.post({
		url: "/user.php",
		parameters : {

		},
		onLoading : function(obj) { 
		
		},
		onComplete : function(obj) { 
			
		},
		onSuccess : function(obj) { 
			var doc = parent.document.getElementById('login_box');
			doc.innerHTML = obj.responseText;
			document.location.href='/download_FreeRM_'+horizontal+'_'+img_id+'.zip';
		},
		onError : function(obj) { alert("Error: " + obj.status); },
		"blad" : "blad"
	});*/
}

function showTickbox(id, value) {
	if(value != 0)
		document.getElementById(id+'_check').innerHTML = "<img src='/_d/buttons/btn_lightbox_add.gif'/>";
}

/**************************************************************************************************************************************/
/** lighbox **/
function Lightbox(action, id, value) {
	if(action == 'delete') {
		var conf = confirm("Are you sure you want to delete this item?");
		if(conf) {
			ManageLightbox(action, id, value);
			TabsContent(4);
		}	
	} else if(action == 'price') {
		ManageLightbox(action, id, value);
		TabsContent(4);
	}
}

function ManageLightbox(action, id, type) {
	jQuery.get("/manage-lightbox.php", { 
			act: action,
			id: id,
			type: type
		},
		function(responseText) {
			if(action != 'delete') {
				var doc = document.getElementById('lightbox_'+id);
				doc.innerHTML = responseText;
				//ReloadSearchResults();
			}	
		}
	, "html");	
}

function Share(asset_id, asset_type) {
	var url = '';

	//if(asset_id == -1)
	//	url = '/share.html?asset_id=' + asset_id + '&asset_type=' + asset_type;
	//else
	url = '/share.html?asset_id=' + asset_id + '&asset_type=' + asset_type;
	jQuery.lightbox().show(url , {'modal' : true, 'width' : 640, 'height' : 500});	
}

function AddBasket(asset_id, asset_type) {
	var url = '';
	
	switch(asset_type) {
		case 1:
			url = '/license-calculator.html?asset_id=' + asset_id + '&asset_type=' + asset_type;
		break;
		case 2:
			url = '/license-calculator.html?asset_id=' + asset_id + '&asset_type=' + asset_type;// + '&keepThis=true&TB_iframe=true&height=300&width=750', '');
		break;
	}
	
	jQuery.lightbox().show(url , {'modal' : true, 'width' : 760, 'height' : 630});	
}

function moreFields(counter) {
	counter++;
	document.getElementById('counter').value = counter;
	var newFields = document.getElementById('readroot').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	var nam="";
	for (var i=0;i<newField.length;i++)
	{
		var theName = newField[i].name;
		nam += theName;
		if(theName == 'friend_name'){
			newField[i].name = theName + counter;
			newField[i].id = theName + counter;
		}
		if(theName == 'friend_email'){
			newField[i].name = theName + counter;
			newField[i].id = theName + counter;
			newField[i].className = theName + counter;
		}
	}
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

/**************************************************************************************************************************************/
/** basket **/

function AddToBasket(asset_type, asset_id, asset_price_id) {
	switch(asset_type) {
		case 1:
			SubmitForm('addToBasketForm');
		break;
		case 2:
			SubmitForm('addToBasketForm', asset_id, asset_price_id);
		break;	
	}
}

function ManageBasket(action, id, value) {
	jQuery.get("/manage-basket.php", { 
			act: action,
			id: id,
			value: value
		},
		function(responseText) {
		}
	, "html");
}


function Basket(action, id, value) {
	if(action == 'delete') {
		var conf = confirm("Are you sure you want to delete this item?");
		if(conf) {
			ManageBasket(action, id, value);
			TabsContent(5);
		}	
	} else if(action == 'price') {
		ManageBasket(action, id, value);
		TabsContent(5);
	}
}

/**************************************************************************************************************************************/
/** filter/advaced search **/

function FilterSearch() {
	var filters = document.getElementById('results_filters').value;
	var query = document.getElementById('search_q').value;
	var category = document.getElementById('category_q').value;
	
	if(document.getElementById('sci').checked)
		var type = 'i';
	else
		var type = 'a';
	
	url = '/filter-search.html?f='+ filters +'&t='+ type +'&c='+ category +'&q='+ query;
	jQuery.lightbox().show(url , {'modal' : true, 'width' : 640, 'height' : 400});
}

function AdvancedSearch() {
	jQuery.lightbox().show('/advanced-search.html' , {'modal' : true, 'width' : 640, 'height' : 450});
}

function Advanced_Search_Filters(fltc_filter_type) {
	jQuery.post("/advanced-search.html", { 
			ajax: 1,
			fltc_filter_type: fltc_filter_type
		},
		function(responseText) {
			var doc = document.getElementById('filters');
			doc.innerHTML = responseText;
		}
	, "html");
}

/**************************************************************************************************************************************/
/** tabs / user area **/

function TabsContent(action, extra_1, extra_2, extra_3, extra_4, extra_5, extra_6, extra_7, extra_8) {
	
	document.getElementById('tab_1').className = '';
	document.getElementById('tab_2').className = '';
	document.getElementById('2').style.display = 'none';
	document.getElementById('tab_3').className = '';
	document.getElementById('3').style.display = 'none';
	document.getElementById('tab_4').className = '';
	document.getElementById('tab_5').className = '';
	document.getElementById('tab_6').className = '';
	if (document.getElementById('tab_7') != null) {
		document.getElementById('tab_7').className = '';
	}
	if (document.getElementById('tab_8') != null) {
		document.getElementById('tab_8').className = '';
	}
	
	document.getElementById('tab_' + action).className = 'tabs-selected';
	if(action == '2' || action == '3') {
		document.getElementById(action).style.display = '';
		var doc = document.getElementById('my-profile-content');
		doc.innerHTML = "";	
	} else {
		var doc = document.getElementById('my-profile-content');
		doc.innerHTML = "<img src='/_d/loading.gif'/>";	
		
		jQuery.get("/manage-profile.php", { 
			  act: action,
			  extra_1: extra_1 || '',
			  extra_2: extra_2 || '',
			  extra_3: extra_3 || '',
			  extra_4: extra_4 || '',
			  extra_5: extra_5 || '',
			  extra_6: extra_6 || '',
			  extra_7: extra_7 || '',
			  extra_8: extra_8 || ''
			},
			function(responseText) {
				var doc = document.getElementById('my-profile-content');
				doc.innerHTML = responseText;
			}
		, "html");
	}
}

/** account / user area **/


/**************************************************************************************************************************************/
/** other functions **/
function checkCountry(value) {
	if(value == '001')
		document.getElementById('stateDIV').style.display = '';
	else
		document.getElementById('stateDIV').style.display = 'none';
		
	var prefix = '+' + value;
	document.getElementById('prefix_telephone').disabled = true;
	document.getElementById('prefix_fax').disabled = true;
	document.getElementById('prefix_telephone').value = prefix; 
	document.getElementById('prefix_fax').value = prefix;
}

function SubmitForm(form_id, extra_1, extra_2, extra_3, extra_4, extra_5, extra_6, extra_7, extra_8) {
	
	var form = document.getElementById(form_id);
	
	var action = jQuery(form).attr('action');
	var formInfo = jQuery(form).serialize(); 
	
	RestoreFormFieldsBorder(form_id);
	
	var submit_value = '';
	if(document.getElementById("submitBtn")) {
		submit_value = document.getElementById("submitBtn").value;
		document.getElementById("submitBtn").value = "Wait...";
	}
	
	jQuery.post(action, { 
			ajax: 1,
			send: 1,
			jquery_data: formInfo,
			extra_1: extra_1 || '',
			extra_2: extra_2 || '',
			extra_3: extra_3 || '',
			extra_4: extra_4 || '',
			extra_5: extra_5 || '',
			extra_6: extra_6 || '',
			extra_7: extra_7 || '',
			extra_8: extra_8 || '',
		},
		function(responseText) {
			if(document.getElementById("submitBtn")) {
				document.getElementById("submitBtn").value = submit_value;
			}
			
			var doc = document.getElementById('info_container');
			var doc_inner = document.getElementById('info_container_inner');
			var doc_message = document.getElementById('message_container');
			var message_inner = document.getElementById('message_container_inner');
			
			if (responseText) {
				var xmlDoc = loadXMLString(responseText);
				
				var root = xmlDoc.getElementsByTagName("ajax")[0];
				var url = xmlDoc.getElementsByTagName("url")[0];
				var mess = xmlDoc.getElementsByTagName("mess")[0];
				
				var message = '';
				var text = '';
				
				if (root) {
					for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
						var node = root.childNodes.item(iNode);
						
						var item_id = node.nodeName;
						
						var type = '';
						if (node.attributes.getNamedItem("type"))
							type = node.attributes.getNamedItem("type").nodeValue;
						
						var msg = ''
						if (node.attributes.getNamedItem("msg"))
							msg = node.attributes.getNamedItem("msg").nodeValue;
						
						var button = '';
						if (node.attributes.getNamedItem("button")) {
							button = '&nbsp;&nbsp;&nbsp;<input type="button" name="modify" value="' + node.attributes.getNamedItem("button").nodeValue + ' " class="btn_extra_large" onclick="' + node.attributes.getNamedItem("button_link").nodeValue + '"/>';
						}
						
						if (type == "error") {
							var item = document.getElementById(item_id);
							if (item) {
								item.style.border = '2px solid #FF0000';
								item.style.backgroundColor = '#FFAFB4';
							}
						} 
						
						message = message + msg + button; 
						if (iNode < root.childNodes.length - 1)
							message += "<br/>";
					}
				}
				else if (url) {
					//alert(url.attributes.getNamedItem("pref").nodeValue);
					if(url.attributes.getNamedItem("scr").nodeValue != '') {
						document.location.href = 'javascript: ' + url.attributes.getNamedItem("scr").nodeValue;
					}
					if(url.attributes.getNamedItem("ref").nodeValue != '') {
						document.location.href = url.attributes.getNamedItem("ref").nodeValue;
					}
					if(url.attributes.getNamedItem("pref").nodeValue != '') {
						parent.document.location.href = url.attributes.getNamedItem("pref").nodeValue;
					}
				}
				else if (mess) {
					var doc_inner = document.getElementById('message_container_inner');
					for (var iNode = 0; iNode < mess.childNodes.length; iNode++) {
						var node = mess.childNodes.item(iNode);
						var item_id = node.nodeName;
						if (node.attributes.getNamedItem("msg"))
							text = node.attributes.getNamedItem("msg").nodeValue;
						
						if (node.attributes.getNamedItem("ref"))
							document.location.href =  node.attributes.getNamedItem("ref").nodeValue;
					
					}
				}
				else
					message = responseText;
				
				if (message != '') {
					doc_inner.innerHTML = message;
					doc.style.display = 'block';
					doc_message.style.display = 'none';
					scroll(0,0);
				}
				
				if (text != '') {
					message_inner.innerHTML = text;
					doc.style.display = 'none';
					doc_message.style.display = 'block';
					scroll(0,0);
				}
			}
		}
	, "html");
}

function RestoreFormFieldsBorder(form_name)
{
	form = document.getElementById(form_name);
	
	for (var iNode = 0; iNode < form.elements.length; iNode++) {
		var node = form.elements[iNode];
		if (node.type != "submit" && node.type != "button") {
			node.style.border = '1px solid #A6A6A6';
			node.style.backgroundColor = '#E8E8E8';
			node.style.backgroundColor = '#FFFFFF';
		}
	}
}

function loadXMLString(txt) 
{
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(txt);
  return(xmlDoc);  
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
	{
	parser=new DOMParser();
	xmlDoc=parser.parseFromString(txt,"text/xml");
	return(xmlDoc);
	}
  catch(e) {alert(e.message)}
  }
return(null);
}

function openpopup(popurl){ 
	winpops=window.open(popurl,"","scrollbars=0,toolbar=0,menubar=0,status=0,resizable=no,screenX=0,screenY=0,left=150,top=0"); 
	//winpops.body.clientWidth=480;
	//winpops.body.clientHeight=730;
	//winpops.moveTo(100,0);
	//winpops.resizeTo(480,730);
}

function appstore(link, message) {
	if(message != '')
		alert(message);
	if(link != '')
		window.open(link);
		//document.location.href = link;	
}

function flashlink(link_main,link, message, status) {
	status = document.getElementById('user_logged_status').value;
	
	if (status == 2) {
		if(message != '')
			alert(message);
		if(link != '')
			openpopup(link);
	}
	else if (status == 1) {
		alert("You are logged in - but in order to access the free online flash versions you must first purchase at least one of our apps from iTunes. Once you have purchased one of the apps, please write a review on iTunes and email a copy to us at 'Reviews@3D4Medical.com' as proof of purchase and we will then register you for access to all online flash apps! Don't forget to include your 3D4Medical.com username when emailing us!");
	}
	else
		alert("You must login to use the online app versions.");
	
	return false;
}

/**************************************************************************************************************************************/
/** subscripton **/

function Subscribe(asset_id, asset_type, asset_price_id) {
	advAJAX.get({
		url: "/subscription.php",
		parameters : {
		  "act" : "add",
		  "asset_id" : asset_id,
		  "asset_price_id" : asset_price_id,
		  "asset_type" : asset_type
		},
		onLoading : function(obj) { 
		
		},
		onComplete : function(obj) { 
			
		},
		onSuccess : function(obj) {
			var docImg = document.getElementById('subscription');
			var docAnim = document.getElementById('subscriptionAnim');
			if(docImg != null)
				docImg.innerHTML = obj.responseText;
			else if(docAnim != null)
				docAnim.innerHTML = obj.responseText;
		},
		onError : function(obj) { alert("Error: " + obj.status); },
		"blad" : "blad"
	});
}

function ShowSubscribtion(user_id) {
	advAJAX.get({
		url: "/subscription.php",
		parameters : {
		  "act" : "check",
		  "user_id" : user_id
		},
		onLoading : function(obj) { 
		
		},
		onComplete : function(obj) { 
			
		},
		onSuccess : function(obj) {
			if(obj.responseText == 1) {
				var doc = document.getElementById('subscription');
				if(doc != null)
					doc.style.display = '';
			}
			if(obj.responseText == 2) {
				var doc = document.getElementById('subscriptionAnim');
				if(doc != null)
					doc.style.display = '';
			}
			if(obj.responseText == 3) {
				var doc = document.getElementById('subscription');
				if(doc != null)
					doc.style.display = '';
				
				var doc = document.getElementById('subscriptionAnim');
				if(doc != null)
					doc.style.display = '';
			}
		},
		onError : function(obj) { alert("Error: " + obj.status); },
		"blad" : "blad"
	});
}

function ModifyImage(img_id, style_id, img_horizontal) {

	url = '/modify-image.html?id='+img_id+'&style='+style_id;
	//jQuery.lightbox().show(url , {'modal' : true, 'width' : 750, 'height' : 720});
	winpops=window.open(url,"","scrollbars=0,toolbar=0,menubar=0,status=0,resizable=no,screenX=0,screenY=0,left=150,top=0,width=750");
}

