function getNum(str)
{
	
	if(typeof(str) != 'undefined' && str != '')
	{
		var r = str.match(/[\d\.]+/g);	
		if(typeof(r) != 'undefined' &&  r &&  typeof(r[0]) != 'undefined')
		{
			return parseInt(r[0]);
		}		
	}
	return 0;
};

function in_array( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
	  if(what == where[i]){
	    a=true;
        break;
	  }
	}
	return a;
}
function processFreePurchase(productId)
{
	if(confirm('Are you sure you want this to be your free package?'))
	{
		$('#modalProcess').jqmShow();
		var options = {
			target:'#modalProcess div.modalProcessSuccessMessage',
			type:'POST',
			beforeSubmit:function()
			{			
				modalProcessMessage('Plese wait while process your request.');	
			},
			success:function()
			{
				
			},
			error:function()
			{
				
			}
		};
		$('#free_product_id').val(productId);
		$('#formPurchaseFreeTemplate').ajaxSubmit(options);		
	}
	return false;
}
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function selectSearchCategory(categoryId)
{
	$('#hidden_category').val(categoryId);
	document.getElementById('search_form').submit();
}

function displayError(error)
{
	$('#modalProcess').jqmShow();
	$('#modalProcess div.modalProcessRetry').hide();
	$('#modalProcess div.modalProcessContainer>div').hide();
	$('#modalProcess div.modalProcessError').show();
	$('#modalProcess div.modalProcessErrorMessage').html(error);
	$('#modalProcess div.modalProcessHeader').show().children().show();
}

function echeck(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		  
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){

		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){

		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

 		 return true;					
	}

function related_add_to_vault(product_id)
{
	var prod = $('#rproduct_id_'+product_id).val();
	add_to_vault('/ajax.php?action=add_to_template_vault&product='+prod);
	
	return false;
}

function add_to_vault(ajax_url)
{
	var myOpen=function(hash)
	{
	    $('input.prettyCheckbox').prettyCheckboxes(); 
	};
	$('#addToVaultModalBody').html("Please wait while processing your request.");
	$("#addToVaultModalBody").load(ajax_url, null, myOpen);
	
	

	$('#addToVaultModal').jqmShow(); 
	return false;
}

function login_first()
{
	$("#addToVaultModalBody").html('<h3>Registered Members Only</h3>Please become a member or log in to add this to your Template Vault.');
	$('#addToVaultModal').jqmShow(); 
	return false;
}

function remove_from_vault(id)
{
	if(confirm('Remove from Template Vault?'))
	{
		$('#fld_product1').val(id);
		$('#remove_from_vault').submit();
	}
	return;
}

function remove_vault_folder(id)
{
	if(confirm('Delete this folder from My Template Vault?'))
	{
		$('#fld_folder1').val(id);
		$('#remove_vault_folder').submit();
	}
}

function remove_my_template(id)
{
	if(confirm('Delete this item from My Templates?'))
	{
		$('#my_template_id').val(id);
		$('#formRemoveMyTemplate').submit();
	}
}

function show_new_folder_dialog()
{
	$('#tvm_form_event').val('newTemplateVaultFolder');
	//$('#fld_folder_id').val();
	$('#templateVaultModal').jqmShow();
}

function show_new_folder_dialog2()
{
	$('#tvm_form_event').val('newStoryboardFolder');
	//$('#fld_folder_id').val();
	$('#templateVaultModal').jqmShow();
}

function show_rename_folder_dialog2(id)
{
	$('#tvm_form_event').val('renameStoryboardFolder');
	$('#fld_folder_id').val(id);
	$('#templateVaultModal').jqmShow();
}

function new_story_folder()
{
	$('#tvm_form_event').val('newStoryboardFolder');
	//$('#fld_folder_id').val();
	$('#templateVaultModal').jqmShow();
}

function show_rename_folder_dialog(id)
{
	$('#tvm_form_event').val('renameTemplateVaultFolder');
	$('#fld_folder_id').val(id);
	$('#templateVaultModal').jqmShow();
}
function loginRequired(url, errorMessages)
{
	$('input.login_url').val(url);
	if(typeof(errorMessages) != 'undefined')
	{
		$('#modalLoginErros').html(errorMessages);
	}
	
	$('#modalLogin').jqmShow();
	return false;
}

function invalidUsernamePass(msg)
{
	
	$('#formModalErrorMessage').html(msg + '<a href="#" onclick="$(\'#modalValidation\').jqmHide(); $(\'#forgotPasswordModal\').jqmShow();">Forgotten Username or Password?</a>');
	$("#modalValidation").jqm().jqmShow();
}

function submitSearch()
{
	var keywords = $('#searchinput').val();
	var error = '';
	if(keywords.length)
	{
		
	}else
	{
		error += 'Please enter keywords\n';
	}
	if(error == '')
	{
		return true;
/*		var url  = $('#searchurl').val() + '~ke-' + encodeURI(keywords);
		
		url += '~co=';
		$('input.components:checked').each(
			function(i)
			{
				url += (i?',':'') + this.value; 
			}
		);
		url += '~ca=';
		$('input.categories:checked').each(
			function(i)
			{
				url += (i?',':'') + this.value; 
			}
		);	


		url += '~fi=';
		$('input.filters:checked').each
		(
			function(i)
			{
				url += (i?',':'') + this.value; 
			}
		);	
		url += '/';
		document.location.href = url;	*/	
	}else
	{
		alert(error);
	}
	return false;
};

function purchaseVideoPackage()
{
	$('#hidden_linkage_type').val('video_package');
	$('#hidden_cost').val($('#total_cost').html());
	$('#hidden_product_id').val(packageId);

	processPurchaseStep1({'linkage_type':$('#hidden_linkage_type').val(), 'cost':$('#hidden_cost').val(), 'product_id':$('#hidden_product_id').val(), 'license':$('input[name=exclusive]:checked').val(), 'url_buy_credits':$('#hidden_url_buy_credits').val(), language:$('#hidden_language').val(), 'url_join_us':$('#hidden_url_join_us').val(), url:$('#url_return').val()});
	return false;
}

function purchaseVideoComponent()
{
	$('#hidden_linkage_type').val('video_component');
	$('#hidden_cost').val($('#compoent_cost').html());
	$('#hidden_product_id').val(componentId);

	processPurchaseStep1({'linkage_type':$('#hidden_linkage_type').val(), 'cost':$('#hidden_cost').val(), 'product_id':$('#hidden_product_id').val(), 'url_buy_credits':$('#hidden_url_buy_credits').val(), language:$('#hidden_language').val(), url:$('#url_return').val()});
	return false;
}

function processPurchaseStep1(data)
{
	
	$('#addToPurchaseModalStep2').hide();
	$('#addToPurchaseModalBody').html('Please wait while processing your request.');
	$('#addToPurchaseModalBody').show();
	
	$('#addToPurchase').jqmShow();
	$('#addToPurchaseModalBody').load(
		$('#formPurchase').attr('action'), 
		data
	);
}
/**
 * Shows the withdraw to paypal modal dialog
 * @return nothing
 */
function showWithdrawPaypal()
{
	$('#withdrawPaypalModalBody1').show();
	$('#withdrawPaypalModalBody2').hide();	
	
	
	
	$('#withdrawPaypal').jqmShow();
}

/**
 * Uses AJAX to submit the withdraw to paypal form and 
 * displays the result in withdrawPaypalModalBody2 div
 * @param ajaxUrl
 * @return nothing
 */
function processWithdrawPaypal(ajaxUrl)
{
	var options = {
			url:ajaxUrl,
			target:'#withdrawPaypalModalBody2',
			type:'POST',
			beforeSubmit:function()
			{
				$('#withdrawPaypalModalBody1').hide();
				$('#withdrawPaypalModalBody2').show();			
				$('#withdrawPaypalModalBody2').html('Please wait while processing your request.');
			},
			success:function()
			{
				
			},
			error:function()
			{
				
			}
		};
		$('#withdrawPaypalForm').ajaxSubmit(options);
}

function processPurchaseStep2(ajaxUrl)
{
	var elemP = $('input[name="p"]:checked').get(0);
	if(typeof(elemP) != 'undefined' && elemP.value == 'join')
	{
		var elemUrlBuyCredit = $('input[name="url_buy_credits_return"]').get(0);

		document.location.href = elemUrlBuyCredit.value;	
	}else
	{
		var options = {
			url:ajaxUrl,
			target:'#addToPurchaseModalStep2',
			type:'POST',
			beforeSubmit:function()
			{
				$('#addToPurchaseModalBody').hide();
				$('#addToPurchaseModalStep2').show();			
				$('#addToPurchaseModalStep2').html('Please wait while processing your request.');
				$('#addToPurchase').jqmShow();
			},
			success:function()
			{
				
			},
			error:function()
			{
				
			}
		};
		$('#formPurchaseStep1').ajaxSubmit(options);		
	}
	

	return false;
}
 	function processPlanPayment(ajaxUrl)
 	{

		var options = {
			url:ajaxUrl,
			target:'#addToPurchaseModalStep2',
			type:'POST',
			beforeSubmit:function()
			{
				$('#addToPurchaseModalBody').hide();
				$('#addToPurchaseModalStep2').show();			
				$('#addToPurchaseModalStep2').html('Please wait while processing your request.');
				$('#addToPurchase').jqmShow();
			},
			success:function()
			{
				
			},
			error:function()
			{
				
			}
		};
		
		$('#formChoosePlan').ajaxSubmit(options);
		return false;
 	}

 	
  	function processPlanPaymentMade(ajaxUrl)
 	{

		var options = {
			url:ajaxUrl,
			target:'#addToPurchaseModalStep2',
			type:'POST',
			beforeSubmit:function()
			{
				$('#addToPurchaseModalBody').hide();
				$('#addToPurchaseModalStep2').show();			
				$('#addToPurchaseModalStep2').html('Please wait while processing your request.');
				$('#addToPurchase').jqmShow();
			},
			success:function()
			{
				
			},
			error:function()
			{
				
			}
		};
		
		$('#formProcessBuyCreditPayment').ajaxSubmit(options);
		return false;
 	}
	
 	
function chooseExclusiveOption(elem)
{

	switch(elem.value)
	{
		case 'non_exclusive':
			$('#total_cost').html(packageInfo.cost);
			break;
		default:
				
			$('#total_cost').html(packageInfo.exclusive_cost);
	}
}

	function processPurchaseCreditPayment(ajaxUrl)
	{
		
		var options = {
			url:ajaxUrl,
			type:'POST',
			dataType:'json',
			beforeSubmit:function()
			{
				modalProcessApplyRetry(processBuyCreditPayment);
				$('#modalProcess').jqmShow();
			},
			success:function(json)
			{
				//alert('hi!');
				if(json.error != '')
				{
					modalProcessError(json.error);
				}else
				{
					modalProcessMessage(json.message);

				}
			}
			
		}
		$('#formProcessBuyCreditPayment').ajaxSubmit(options);
		return false;
	}

function changeComponentType(type)
{
	for(pkg_i in related_components)
	{
		var pkg = related_components[pkg_i];
		for(comp_i in pkg)
		{
			var comp = pkg[comp_i];
			if(comp['product_component'] == type)
			{
				$('#rproduct_code_'+pkg_i).html(comp['code']);
				$('#rproduct_type_'+pkg_i).html(type);
				$('#rproduct_link_'+pkg_i).attr('href','/en/Shop/Package/Component/~product-'+comp_i+'/');
				$('#rproduct_img_'+pkg_i).attr('src','/products/'+comp['hash']+'/preview_small.jpg');
				$('#rproduct_length_'+pkg_i).html(comp['video_time']);
				$('#rproduct_id_'+pkg_i).val(comp_i);
			}
		}
	}
	
}
	
function selectPackageComponent(component_id)
{
	$('.also_like').hide();
	$('.componentAll').fadeIn('slow');
	$('#storyBoardButton').show();
	
	var d = components[component_id];
	componentId = d.product_id;
    
	$('td.tdPackageTitle a').each(function()
	{
	    if($(this).hasClass('active'))
	    {
	        $(this).removeClass('active');
	    }
	});
	
	$('#componentTitle' + componentId).addClass('active');

	for(var i in d)
	{
		if(typeof(d[i]) != 'function')
		{
			switch(i)
			{
				case 'status_image':
				case 'status_video':
				case 'status_sound':
				case 'status_font':
					
					$('#' + i + "_link_url").removeClass("status_url_active");
					if(d[i] == 'Available for purchase')
					{
						
					
						$('#' + i + "_link_url").addClass("status_url_active").unbind().click(
							function()
							{
								viewAvailableElements(componentId);
								return false;								
							}
						);						
					}else
					{
						$('#' + i + "_link_url").unbind().click(
							function()
							{
								
								return false;
							}
						);
					}
					break;
			}			
			$('#' + i).html(d[i]);
		}
	}
	$('.component').each(
		function()
		{
			if($(this).hide().hasClass('players'))
			{				
				$(this).empty();
			}
		}
	);
	
	$('.component' + componentId).each(
		function()
		{
			if($(this).show().hasClass('players'))
			{
				addPlayer($(this).css('display', 'block').attr('id'));
			}
		}
	);
	
	changeComponentType(d.product_component);
	
	return false;
}

function changePassword(elem)
{
	if(elem.checked)
	{
		$('.changePassword').show();
	}else
	{
		$('.changePassword').hide();
	}
}

function selectAbout(elem)
{
	var defaultValue = 'Please specify...';
	$('#about_us_other').focus(
					function()
					{
						if(this.value == defaultValue)
						{
							this.value = '';
						}
					}
				).blur(
					function()
					{
						
						if(this.value == '')
						{
							this.value = defaultValue;
						}
					}
				);	
	if(elem.value == 'Blog' || elem.value == 'Forum' || elem.value == 'Other' )
	{
		if($('#about_us_other').val() == '')
		{
			$('#about_us_other').val(defaultValue);
		}
		$('#areaAboutUs').show();
	}
	else
	{
		$('#about_us_other').val('');
		$('#areaAboutUs').hide();
	}
	
}

function hide(trigger, id)
{
    $(id).css('visibility', (trigger.checked === true)?'hidden': 'visible');
}
function changeSearchComponent(elem, url)
{
	document.location.href = url.replace('SSCC', elem.value);
}

function changeSearchFileType(elem, url)
{
	document.location.href = url.replace('SSFF', elem.value);
}

