      $(function()
		{
			$('.searchControlCover').corner("top round 10px");
			$('.templateDetailsPages').corner("top round 10px cc:#E8E8E8");
			$('.templateDetailsFields').corner("top round 10px cc:#E8E8E8");
			$('.templatePreviewButton').corner("top round 10px cc:#E8E8E8");
			//$('.defaultSubscriptionGroup').corner("top round 10px");
			//$('.defaultSubscriptionGroupHeader').corner("top round 10px");
			//$('.defaultSubscriptionSubDetailsCostPrice>div').corner("round 50px cc:#E8E8E8");
			$('.defaultSubscriptionSub').corner("round 10px");
			$('.defaultSubscriptionSubDetailsCostBuy').corner("round 5px");
			$('.defaultSubscriptionSubDetailsCost').corner("round 50px;");
			$('.subFeatureTable').corner("round 5px");
			$('#divValRules').corner("round 8px");
			$('#configControlForm').corner("round 8px");
			$('#configControlForm>p').corner("top round 8px");
			$('#divFormNormal').corner("round 8px");
			$('#divFormNormal>p').corner("top round 8px");
			$('#productForm').corner("round 8px");
			$('#productForm>p').corner("top round 8px");
			$('.versionControlRight').corner("round 15px");
			$('.editEntitySubscription').corner("top round 15px");
			$('.VoucherRefCell').corner("round 8px");
			$('.roleEntityTypes>div').corner("round 8px");
			$('.productTradeSeetingInfo').corner("round 5px");
			$('.productTradeSeetingInfo>p').corner("top round 5px");
			$('.subGroupSubscriptions').corner("round 5px");
			$('.subGroupSubscriptions>p').corner("top round 5px");
			$('.subGroupSubscriptions>.genericTable').corner("round 5px");
			$('.certList').corner("round 8px");
			$('.selectedTxtHeader').corner("top round 6px");
			$('.imageDialogHeader').corner("top round 6px");
			
			$('.defaultHomeSingleMerchant').corner("round 10px");
			$('.defaultHomeSingleMerchant>p:nth-child(1)').corner("round 7px");
			$('.defaultHomeSingleMerchant>span').corner("round 8px");
			
			$('.defaultHomeMultiMerchant').corner("round 10px");
			$('.defaultHomeMultiMerchant>p:nth-child(1)').corner("round 7px");
			$('.defaultHomeMultiMerchant>span').corner("round 8px");
			$('.defaultHomePageTutorials').corner("round 10px");
			$('.defaultHomePageLeft img').corner("round 10px");
			$('.tutorialListHeader').corner("round 20px");
			$('.aboutMain>p').corner("round 10px");
			$('.aboutMainContentRequirements').corner("round 10px");
			$('.aboutMainContentContactInfo').corner("round 10px");
			$('.aboutMainContentRight>p').corner("round 10px");
			$('.aboutMainContentRight').corner("round 10px");
			$('.aboutMainContentRight>.aboutMainContentContactForm').corner("round 10px");
			$('.section_leftmenus>div').corner("round 10px");
			$('.section_leftmenus>div .leftMenuHeaderPara').corner("top round 10px");
			$('.verticalUserMenu').corner("bottom round 10px");
			$('.section_leftmenus>div .userMenuTextCollapsed').corner("bottom round 10px");
			//$('.headerArea').corner("top round 5px");
			$('.loginSection').corner("round 10px");
			$('.loginSection>a>p').corner("round 10px");
			$('.loginSection>p>a>span').corner("round 10px");
			$('.mediaButton').corner("round 10px");
			$('.layoutApplyMessageErrors').corner("round 10px");
			$('.layoutApplyMessageNoErrors').corner("round 10px");
			$('.deleteCollectionItem').corner("round 8px");
			$('.addNewCollectionItem').corner("round 8px");
			$('.functionButtons li').corner("top round 8px");
			$('.addressView p').corner("bottom right round 8px");
			$('.addressView').corner("bottom right round 8px");
			$('.addNewAddress').corner("top round 8px");
			
			//========Magrosa.com only============
			$('.clsMagrosaMenu>li').corner("top round 8px");
			$('.clsMagrosaMenu>li:hover').corner("top round 8px");
			$('.magrosaMenuBarLogoArea').corner("top round 8px");
			$('.magrosaMenuBarLogoArea>a>img').corner("top round 8px");
			$('.section_leftmenus').corner("round 10px");
			$('.divPageHeader').corner("top left round 10px");
			$('.divPageMenu').corner("bottom round 8px");
			$('.breadcrumb').corner("bottom round 8px");
			$('.section_cartsummary').corner("round 15px");
			$('.magrosaHeader').corner("right bottom  round 10px");
			$('.magrosaHeaderLoginAreaBox').corner("bottom  round 10px");
			//$('.magrosaHomePage').corner("top round 10px");
			$('.magrosaHomePageMainImage').corner("bottom round 10px");
			$('.magrosaHomePageAdvertInfo').corner("top round 10px");
			$('.magrosaAboutPageImage').corner("right bottom  round 10px");
			$('.magrosaAboutPageContactDetailsRight').corner("round 5px");
			$('.magrosaAboutPageContactDetailsRight > p').corner("round 5px");
			$('.aboutMainContentContactForm').corner("round 5px");
			$('.aboutHeading').corner("round 8px");
			$('.magrosaAboutPageContactDetailsLeft').corner("round 10px");
			
			$('.magrosaHowToPage').corner("round 8px");
			$('.magrosaHowToPageHeader').corner("round 8px");
			$('.magrosaHowToPageContents').corner("round 8px");
			$('.magrosaHowToPageContentsLeft').corner("round 8px");
			$('.magrosaHowToPageContentsRight').corner("round 8px");
			$('.magrosaHowToMore').corner("round 8px");
			$('.footer').corner("round 8px");
			$('.magrosaTermsHeader').corner("top left round 10px");
			$('.magrosaTermsHerderSub').corner("bottom round 10px");
			//==================================
			
			
			$('.borderedTable tr:odd').addClass('odd');
			$('.borderedTable tr:even').addClass('even');
			$('.innerOrderdetails tr:even').addClass('even');
			$('.innerOrderdetails tr:odd').addClass('odd');
			$('#tblPermissions tr:odd').addClass('odd');
			$('#tblPermissions tr:even').addClass('even');
			$('#tblSettings tr:odd').addClass('odd');
			$('#tblSettings tr:even').addClass('even');
			
			$('.tblShoppingCart tr:even').addClass('even');
			$('.tblShoppingCart tr:odd').addClass('odd');
			$('.imageDialog').hide();
			$('.busyBox').hide();
			$('.ucBox').hide();
			$('.qtyUpdateSpan').hide();
			$('.selctPaymentCartArea').hide();
			$('.btnVoucherTransfer').hide();
			$('.voucherToMessageRow').hide();
			$('.businessSubCategoryGroup').hide();
			
			
			$('.voucherRedeemUseColumn').hide();
			
			var redeemVal = $('#validationfail').val();
			if(redeemVal=='True')
				{
					$('.voucherRedemptionQuestions').hide();
					$('.voucherRemptionSecondPart').hide();
					$('.btnVoucherRedemptionFinish').hide();
				}
			else
				{
					$('.voucherRedemptionQuestions').show();
					$('.voucherRemptionSecondPart').show
					$('.btnVoucherRedemptionFinish').show();
				}
				
			var h = $('#divMainContent');
			var tt =h.height();
			$('#divLeftMenus').height(tt-2);
			
			//Template data action field visibility
			var tempId = 0;
			tempId = $('#templateid').val();
			if(tempId == 0)
			{
				$('.templateDataAction').hide();
				$('#tDataDiv').hide();
			}
			
			var showAte=$('#showatefacts').val();
			if(showAte=='true')
			{$('.bankDepositArtefacts').show();}
			else
			{$('.bankDepositArtefacts').hide();}
			
			$('.pageListSearchControl').hide();
			$('.serchControlOpenCloseLink').addClass('toggleOffRight');
			$('.userMenuText').addClass('activePointer');
			
			$('.listColumnHeaderSearchBox').hide();
			//dialog window
			//the button to show the editor has class 'simpleModal'
			//the button has custom attribute 'txtname' which is the id of the textbox to edit
		
		//$('.emptyCart').unbind('click');
		//$('.emptyCart').bind('click',function()
		//	{
		//		$.getJSON('/Cart/Clear',{},function(jResult)
		//			{
		//				alert(jResult.Message);
		//			}
		//		);
		//		
		//	}
		//);
		
		
		$('input[type="text"],input[type="password"],select,textarea').bind('keypress change focus ',function()
			{
				if($(this).attr('id') != 'txtSearch')
					{
						$(this).addClass('selectedInput');
					}
			}
		);
		$('input[type="text"],input[type="password"],select,textarea').bind('blur',function()
			{
				if($(this).attr('id') != 'txtSearch')
				{
					$(this).removeClass('selectedInput');
				}
			}
		);
		$('.userMenuText').click(function()
			{
				if($('#section_usermenu>ul').is(':visible'))
					{
					  $(this).addClass('userMenuTextCollapsed');
					 $('.section_leftmenus>div .userMenuText').corner("round 10px");
					 $('#section_usermenu>ul').hide('slow');
					}
				else
					{	
						$(this).removeClass('userMenuTextCollapsed');
						$('.section_leftmenus>div .userMenuText').corner("top round 10px");
						$('#section_usermenu>ul').show('slow');
					}
			}
		);
		
		 $('.btnEditor').click(function()
			 {
				
				var txtId =$(this).attr('txtboxid');
				var pageName =$(this).attr('pagename');
				$('#selectedTxtHeaderPara').html(pageName);
				$('#dialogEditor').val($('#'+txtId).val());
				$('#dialogBox').modal();
				
				 $('#dialogEditor').htmlarea( {toolbar: [
                     ["html"], 
				 	["bold", "italic", "underline", "strikethrough", "|", "subscript", "superscript"],
				 	["increasefontsize", "decreasefontsize"],
				 	["orderedlist", "unorderedlist"],
				 	["indent", "outdent"],
				 	["justifyleft", "justifycenter", "justifyright"],
				 	["link", "unlink", "image"],
				 	["p", "h1", "h2", "h3", "h4"],
				 	["cut", "copy", "paste"],                   
                     [{
                         // This is how to add a completely custom Toolbar Button
                         css: "custom_disk_button",
                         text: "Save",
                        action: function(btn) {
                             // 'this' = jHtmlArea object
                             // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button
                             alert('This function updates the text box with your changes, you need to update page to persist your changes');
				 			$('#'+txtId).val(this.toHtmlString());
                         }
                     }]
                 ]});
				 //$('#dialogEditor').show();

			 });
	//	$('#btnApplyTheme').click(function()
	//		{
	//			var tId =$('#themeid').val();
	//			var pType = $('#pagestypes').val();
	//			alert('here');
	//			$.getJSON('/ContentManagement/ApplyTheme',{themeId:tId,pageType:pType },
	//					function(jResult)
	//						{
	//							if(jResult.Success == 1)
	//							{
	//								alert('Layout applied succesfuly to all pages.');
	//							}
	//							else
	//							{
	//								alert(jResult.Message);
	//							}
	//						}
	//					);
	//		}
	//		);
			
			$('#btnFinished').click(function()
				{
					$('.busyBox').hide();
					$.modal.close();
				}
			);
			
			
		$('.resourceFileAction').click(function()
			{
				var resId = $(this).attr('resourceid');
				$.getJSON('/Resource/Preview',
					{resourceId:resId},
					function(jResult)
						{
							if(jResult.Success==1)
								{
									if(jResult.Type==5) //Text document
										{
											$('#selectedTxtHeaderPara').html(jResult.FileName);
											$('#dialogEditor').val(jResult.ResourceData);
											$('#dialogBox').modal();
											$('#dialogEditor').htmlarea( {toolbar: [
												["html"], 
												["bold", "italic", "underline", "strikethrough", "|", "subscript", "superscript"],
												["increasefontsize", "decreasefontsize"],
												["orderedlist", "unorderedlist"],
												["indent", "outdent"],
												["justifyleft", "justifycenter", "justifyright"],
												[{
													css:"custom_internal_link_button",
													text:"Insert page link",
													action:function(btn)
													{

														var obj = this;
														var selected='';
														$('.customPrompt').attr('title','Link to page');
														$('.customPrompt').load('/ContentManagement/ViewItemsCombo?type=1&nameValue=true&selectName=selectPage');
														$('.customPrompt').dialog({
																					height: 180,
																					modal: true,
																					buttons:{
																								
																								"Cancel":function()
																												{
																													$( this ).dialog( "close" );
																												},
																								"Select page":function()
																												{
																													selected = $('#selectPage').val();
																													obj.execCommand("createLink", false, "/Home/Page/" + selected);
																													$( this ).dialog( "close" );
																												}
																								
																								
																							}
																				});
													}
												},
												"link", "unlink", "image",
												{
													css:"custom_internal_image_button",
													text:"Insert image (resource)",
													action:function(btn)
													{
														var obj = this;
														var selected='';
														$( '.customPrompt').attr('title','Insert image from resource');
														$( '.customPrompt').load('/ContentManagement/ResourceList?resType=2&selectName=fieldvalue_1');
														
														$('.customPrompt').dialog({
																					height: 180,
																					modal: true,
																					buttons:{
																								
																								"Cancel":function()
																												{
																													$( this ).dialog( "close" );
																												},
																								"Select image":function()
																												{
																													selected = $('#fieldvalue_1').val();
																													obj.execCommand("insertImage", false, "/Zip/Image?res=" + selected);
																													$( this ).dialog( "close" );
																												}
																								
																								
																							}
																				});
													}	
												}
												],
												["p", "h1", "h2", "h3", "h4"],
												["cut", "copy", "paste"],                   
												[{
												 // This is how to add a completely custom Toolbar Button
												 css: "custom_disk_button",
												 text: "Save",
												action: function(btn) {
													 // 'this' = jHtmlArea object
													 // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button
														alert('Changes will be saved to file.');
														$.getJSON('/Resource/SaveText',{resourceId:jResult.ItemId,content:this.toHtmlString()},
														          function(jRes)
																  {
																	alert(jRes.Message);
																  }
														);
													}
												}]
												
												]});
											
										}
									if(jResult.Type==2) //Image
										{
											
											//$('.imageDialogDetails').html(jResult.Attributes[0].Name);
											$('#fileName').html(jResult.FileName);
											$('.imageDialogImage').html('<span><img src="' + jResult.ResourceUrl + '" /></span>');
											$('.imageDialog').modal();											
										}
								}
							else //failed
								{
									alert(jResult.Message);
								}
						}
				);
			}
			
		);
		
		$('.templatePreviewButton span.templateEdit').click(function()
			{
				var tempId = $(this).attr('id');
				var template =$(this).attr('template');
				var action ='';
				var saveAction ='';
				if(template != '')
					{
						if(template == 'page')
						{
							action ='/Template/ContentEdit';
							saveAction ='/Template/SaveChanges';
						}
						if(template == 'email')
						{
							action ='/EmailTemplate/ContentEdit';
							saveAction ='/EmailTemplate/SaveChanges';
						}
						if(template == 'layout' || template == 'control')
						{
							action ='/ContentManagement/ContentEdit';
							saveAction ='/ContentManagement/SaveChanges';
						}
					}
				if(action != '' &&  saveAction !='')
				{
					$.getJSON(action,
								{templateId:tempId},
								function(jResult)
									{
									
									if(jResult.Success==1)
										{
												$('#selectedTxtHeaderPara').html(jResult.FileName);
												$('#dialogEditor').val(jResult.Content);
												$('#dialogBox').modal();
												$('#dialogEditor').htmlarea( {toolbar: [
													["html"], 
													["bold", "italic", "underline", "strikethrough", "|", "subscript", "superscript"],
													["increasefontsize", "decreasefontsize"],
													["orderedlist", "unorderedlist"],
													["indent", "outdent"],
													["justifyleft", "justifycenter", "justifyright"],
													[{
														css:"custom_internal_link_button",
														text:"Insert page link",
														action:function(btn)
														{

															var obj = this;
															var selected='';
															$('.customPrompt').attr('title','Link to page');
															$('.customPrompt').load('/ContentManagement/ViewItemsCombo?type=1&nameValue=true&selectName=selectPage');
															$('.customPrompt').dialog({
																						height: 180,
																						modal: true,
																						buttons:{
																									
																									"Cancel":function()
																													{
																														$( this ).dialog( "close" );
																													},
																									"Select page":function()
																													{
																														selected = $('#selectPage').val();
																														obj.execCommand("createLink", false, "/Home/Page/" + selected);
																														$( this ).dialog( "close" );
																													}
																									
																									
																								}
																					});
														}
													},
													"link", "unlink", "image",
												{
													css:"custom_internal_image_button",
													text:"Insert image (resource)",
													action:function(btn)
													{
														var obj = this;
														var selected='';
														$( '.customPrompt').attr('title','Insert image from resource');
														$( '.customPrompt').load('/ContentManagement/ResourceList?resType=2&selectName=fieldvalue_1');
														
														$('.customPrompt').dialog({
																					height: 180,
																					modal: true,
																					buttons:{
																								
																								"Cancel":function()
																												{
																													$( this ).dialog( "close" );
																												},
																								"Select image":function()
																												{
																													selected = $('#fieldvalue_1').val();
																													obj.execCommand("insertImage", false, "/Zip/Image?res=" + selected);
																													$( this ).dialog( "close" );
																												}
																								
																								
																							}
																				});
													}	
												}],
													["p", "h1", "h2", "h3", "h4"],
													["cut", "copy", "paste"],                   
													[{
													 css: "custom_disk_button",
													 text: "Save",
													action: function(btn) {
															alert('Changes will be saved to file.');
															$.getJSON(saveAction,{virtPath:jResult.VirtualPath,content:this.toHtmlString(),templateId:tempId},
																	  function(jRes)
																	  {
																		alert(jRes.Message);
																	  }
															);
														}
													}]
													]});
										}
									else
										{
											alert(jResult.Message);
										}
									}
						
							);
				}
				else
				{alert('Type of trmplate to edit is not defined.');}
			}
			);
			
		//View item version publish/de-publish
		$('#versionapproved').click(function()
				{
					var chk;
					var pId = $('#persid').val();
					if($(this).is(':checked'))
						{chk='true';}
					else
						{chk='false';}
						
					$.getJSON('/ContentManagement/PublishVersion',{approved:chk,persId:pId},
							function(jResult)
								{
									alert(jResult.Message);
								}
							);
				}
			);
			
		//Change version number	
		$('#versionnumber').change(function()
				{
					var viewId =$('#id').val();
					var verNum =$(this).val();
					var sURL = '/ContentManagement/Edit/' + viewId + '?versionNumber='+ verNum; 
					window.location.replace(sURL);
				}
			);
		$('.deleteVersion').click(function()
				{
					var count =$('#versionnumber option').length;
					if((count==1) || (count==0))
						{alert('This is the only version, you can not delete it.');}
					else
						{
							//Now we can remove this item
							var pId = $('#persid').val();
							$.getJSON('/ContentManagement/DeleteVersion',{persId:pId},
									function(jResult)
										{
											alert(jResult.Message);
											window.location.reload();
										}
									);
						}
				}
			);
		//Preview version
		$('.previewVersion').click(function()
			{
				var verNum = $('#versionnumber').val();
				var fileType = $('#fType').val();
				var id = $('#id').val();
				
				window.open('/Template/Preview/' + id + '?versionNumber=' + verNum + '&fType=' + fileType);
			}
		);
		
		//Updating order payment details for bank deposit
		$('.cmbEditOrderStatus').change(function()
				{
					var value = $(this).val();
					var gwayName =$('#gwayname').val();
					var oId =$('#orderid').val();
					if((value=='12') && (gwayName=='BankDeposit'))
					{
						$('.bankDepositArtefacts').load('/Order/BankDepositDetails',{orderId:oId});
						$('.bankDepositArtefacts').show();
					}
					else
					{
						$('.bankDepositArtefacts').hide();
					}
				}
			);
			
		//View deposit payment proof
		$('.bankDepositProof').live('click',function()
				{
					var oId =$('#orderid').val();
					$('#depositProofImage').html('<p class="closeProof activePointer">Close this image</p>' + 
													'<img id="proofImg" src="/Zip/PaymentProof?orderId=' + oId + '"></img>' +
													'<p class="changeProof activePointer">Change proof image</p>');
					$('#depositProofImage').show();
				}
			);
			
			
		$('.closeProof').live('click',function()
				{
					$('#depositProofImage').hide();
				}
			);
			
		$('.changeProof').live('click',function()
				{
					$('#depositProofImage').html('<input id="proofimage" class="" type="file" value="" name="proofimage">');
				}
			);
			
		//Display proof details
		$('.viewProofDetails').click(function()
				{
					
					var gwayName =$('#gwayname').val();
					var oId =$('#orderid').val();
					
					if(gwayName=='BankDeposit')
						{
							$('.bankDepositArtefacts').load('/Order/BankDepositDetails',{orderId:oId});
							$('.bankDepositArtefacts').show();
						}
				}
				
			);
		//Close all proof details
		$('.proofAreaClose').live('click',function()
				{
					$('.bankDepositArtefacts').hide();
				}
			);
		//Bank country changed
			$('.cmbBankCountries').live('change',function()
					{
						var selected = $(this).val();
						var gName =$('#gwayname').val();
						$('.cmbSelectedCountryBanks option').each(function()
								{
									$(this).remove();
								}
							);
						$.getJSON('/Order/BanksInCountry',
							{countryCode:selected,gatewayName:gName},
							function(jResult)
							{
								
								if(jResult != null)
									{
										for (var i = 0; i < jResult.length; i++) 
											{  
												$('.cmbSelectedCountryBanks').append('<option value="' + jResult[i].BankName + '">' +  jResult[i].BankName + '</option>');
											}
									}
							}
						);
					}
				);
		//Close modal	
		$('#imgDialogClose').click(function()
			{
				$.modal.close();
			}
		);
		 
		$('.tblShoppingCart tr').mouseover(function()
			{
				var tr = this;
				var trId = tr.id;
				$('#spnLabel_' + trId).hide();
				$('#spnUpdate_' + trId).show();
				$(tr).addClass('cartRowHover');
			}
			);
		$('.tblShoppingCart tr').mouseout(function()
			{
				var tr = this;
				var trId = tr.id;
				
				$('#spnUpdate_' + trId).hide();
				$('#spnLabel_' + trId).show();
				$(tr).removeClass('cartRowHover');
			}
			);
			
		$('.oderDetailsLink').click(function()
			{
			
				if($('.divOrderDetails').is(":visible"))
					{
						$('.divOrderDetails').hide();
						$('.oderDetailsLink').removeClass('toggleOn');
						$('.oderDetailsLink').addClass('toggleOff');
					}
				else
					{
						$('.divOrderDetails').show();
						$('.oderDetailsLink').removeClass('toggleOff');
						$('.oderDetailsLink').addClass('toggleOn');
					
					}
					
				
				
			}
		);
		
		$('.configAccountsEmailTemplates>p').click(function()
			{
				if($('.emailTemplatesTable').is(":visible"))
					{
						$('.emailTemplatesTable').hide();
						$(this).removeClass('toggleOn');
						$(this).addClass('toggleOff');
					}
				else
					{
						$('.emailTemplatesTable').show();
						$(this).removeClass('toggleOff');
						$(this).addClass('toggleOn');
					}
			}
		);
		
		
		$('.orderDetailsMerchantHeader').click(function()
			{
				
				var toggleId = $(this).attr('id') + 'branches';
				if($('#'+ toggleId).is(":visible"))
					{
						$('#'+ toggleId).hide();
						$(this).removeClass('toggleOn');
						$(this).addClass('toggleOff');
					}
				else
					{
						$('#'+ toggleId).show();
						$(this).removeClass('toggleOff');
						$(this).addClass('toggleOn');
					
					}
			}
		);
		
		
		
		$('.paymentMethodCart>p').click(function()
			{
				if($('.paymentMethodCart>div').is(':visible'))
					{
						$(this).removeClass('toggleOn');
						$(this).addClass('toggleOff');
						$('.paymentMethodCart>div').hide();
					}
				else
					{
						$(this).addClass('toggleOn');
						$(this).removeClass('toggleOff');
						$('.paymentMethodCart>div').show();
					}
			}
		);
		
		$('.paymentSelectCombo').change(function()
			{
				var selected =$(this).val();
				
				$('.pamentMethodDescription').load(
					'/Gateway/Description',
				{ gatewayId: selected });
				
				
				$('.bankDepositCountries').load(
					'/Cart/CountriesWithBanks',
				{ gatewayId: selected });
			}
		);
		
		$('.addBtn').click(function()
			{
			$(this).addClass('addBtn form_btn form_btn_nobottom');
			}
				
		);
		
		$('.clearCart').click(function()
			{
				$('.cartAreaSpacer').hide();
				$('#divCart').load('/Cart/Clear');
				window.location.reload();
			}
		);
		
		//ViewItem file upload box
		$('#itemfile').change(function()
			{
				var fileName = $(this).val();
				fileName=fileName.substring(0,fileName.lastIndexOf('.')).toLowerCase();
				
				if($('#itemname').attr('readonly')==true)
					{$('#itemname').removeAttr('readonly');}
				$('#itemname').val(fileName);
				$('#itemname').attr('readonly',true);
				
				
			}
		);
		
		//Email template FromAddress changed - this changes the email format to match the email format
		$('#fromaddress').change(function()
			{}
		);
		
		//Validation value type changed 
		$('.spanValidationValueType').change(function()
			{	
				var cntrlId =$(this).attr('id').toLowerCase();
				var spanId = 'spn_' + cntrlId;
				var selectedValue = $(this).val();
				var targetSpan = spanId.substring(0,spanId.lastIndexOf('_') + 1) + 'value';
				var selName = targetSpan.substring(targetSpan.indexOf('_') + 1)
				
				$('#' + targetSpan).load('/Rules/PageFieldList',{selectName:selName,fieldType:selectedValue});
			
				
			}
		);
		
		/*Branches Units validation*/
		/*--Branch check box selection--*/
		$('.chkBranch').click(function()
			{
				var selected = $(this).is(':checked');
				var branchId = $(this).attr('id').substring($(this).attr('id').indexOf('_') + 1);
				var unitsBoxId = 'branchunits_' + branchId;
				
				if((selected==true) && (Number($('#'+ unitsBoxId).val()) == 0))
					{
						$('#'+ unitsBoxId).addClass('input-validation-error');
						alert('Add number of product units in this branch');
					}
				else
					{
						$('#'+ unitsBoxId).removeClass('input-validation-error');
						$('#'+ unitsBoxId).val(0);
					}
			}
		);
		/*--Units update--*/
		$('.unitsBox').bind('keypress change focus ', function()
			{
				var branchId = $(this).attr('id').substring($(this).attr('id').indexOf('_') + 1); 
				var chkBranch = 'branch_' + branchId;
				var selected = $('#'+chkBranch).is(':checked');
				
				if((Number($(this).val())>0) && (selected==true))
					{
						$(this).removeClass('input-validation-error');
					}
				if((Number($(this).val())==0) && (selected==true))
					{
						$(this).addClass('input-validation-error');
					}
				
			}
		);
		$('table td img.btnDelete').live('click',function()
			{     
				
				$(this).parent().parent().remove(); 
			}
		);
		
		$('.chkAutoChekPasswordStrenght').click(function()
			{
				if($(this).is(':checked'))
					{$('.pwdStrengthRegex').removeClass('hiddenItem');}
				else
					{$('.pwdStrengthRegex').addClass('hiddenItem');}
			}
		);
		
		$('.pwdValidation').keyup(function()
			{
				var pwd =$(this).val();
				$.getJSON('/Account/CheckPasswordStrength',{password:pwd},function(jResult)
					{
						if(jResult != null)
						{
							if(jResult.NewStrength==1) //weak
								{
									$('.passwordStrength').html('<div class="weakPassword">Password is weak!</div>');
								}
							
							if(jResult.NewStrength==2) //medium
								{
									$('.passwordStrength').html('<div class="mediumPassword">Medium strength</div>');
								}
							
							if(jResult.NewStrength==3) //strong
								{
									$('.passwordStrength').html('<div class="strongPassword">Strong</div>');
								}
						}
					}
				);
			}
		);
		
		$('.btnDeleteField').click(function()
			{
				var fldId= $(this).attr('fieldid');
				
				if(confirm('All data that belongs to this field will also be deleted!.'))
					{
						
						$.getJSON('/Rules/DeleteField',{fieldId:fldId},
									function(jResult)
										{
											if(jResult.Success==1)
												{
													$(this).parent().parent().remove();
													window.location.reload();
												}
											alert(jResult.Message);
											
										}
									);
						 
					}
			}
		);
		
		$('#redeemmethod').change(function()
			{
				var vId = $('#voucherid').val();
				var redeem = $(this).val();
				$('.voucherSettings').load('/Voucher/VoucherSettings?voucherId=' + vId + '&selectedRedeem=' + redeem);
			}
		
		);
		
		$('.vMerchant').click(function()
			{
				if($(this).is(':checked'))
					{$(this).parent().addClass('selectedVoucherMerchant');}
				else
					{$(this).parent().removeClass('selectedVoucherMerchant');}
			}
		);
		
		$('.voucherActivate').click(function()
			{
				var myName =$(this).attr('id');
				if($(this).is(':checked'))
					{
						var vId =$('#voucherid').val();
						
						
						
						if(vId==0)
						{alert('This Voucher has not been paid for. Check out and make payment before activating for use.');}
						else
						{
							
							$.getJSON('/Voucher/Activate',
										{voucherId:vId},
										function(jResult)
											{
												if(jResult.Success=='0')
													{
														$('#'+ myName).removeAttr('checked');
														alert(jResult.Message);
															
													}
											}
									);
						
						}
						
						
					}
								
			}
		);
		
		$('.voucherRedemptionMethodSelected').change(function()
			{
				var red =$(this).val();
				$('.voucherRedemptionQuestions').show();
				$.get('/Voucher/QuestionProgress?redeemMethod=' + red + '&lastCheck=',
						function(data)
							{
								$('.voucherRedemptionQuestions').append(data);
							}
					);
			}
		);
		
		$('.voucherQuestionPassed').live('click',function()
			{
				var red =$('.voucherRedemptionMethodSelected').val();
				var id =$(this).attr('id');
				var index= id.substring(id.indexOf('[')+1);
				index=index.substring(0,index.indexOf(']'));
						
				var cls  = 'name_'+ index ;
				var ans = $('.' + cls).val();
				
				if($(this).is(':checked'))
					{
						
						
						$.get('/Voucher/QuestionProgress?redeemMethod=' + red + '&lastCheck='+ ans, 
								function(data)
									{
										$('.voucherRedemptionQuestions').append(data);
									}
								);
						//$('.row_' + index).removeClass('VoucherSecurityRowFailure');
					}
					
				else
					{
						
						
						$.getJSON('/Voucher/CheckMustPass',
									{name:ans},
									function(jResult)
									{
										if(jResult.Success=='0')
										{
											$('.btnVoucherRedemptionFinish').hide();
											//$('#row_1').addClass('VoucherSecurityRowFailure');
											alert(jResult.Message);
										}
									}
									);
					}
			}
		);
		
		$('.voucherQuestionsCompleted').live('click',function()
			{
				var red =$('.voucherRedemptionMethodSelected').val();
				
				$.getJSON('/Voucher/MethodAmount',
							{redeemMethod:red},
							function(jResult)
								{
									$('#amountclaimed').val(jResult.Message);
								}
							);
				$('.btnVoucherRedemptionFinish').show();
				$('.voucherRemptionSecondPart').show();
			}
		);
		
		$('.btnVoucherRedemptionFinish').click(function()
			{
				if($('#cashed').is(':checked'))
					{
						return true;
					}	
				else
					{
						alert('You need to select Charge voucher');
						$('#cashed').addClass('input-validation-error');
						return false;
					}
				
			}
		);
		
		$('.btnTransferCheckUser').click(function()
			{
				var vId =$('#id').val();
				var uName =$('#username').val();
				$.getJSON('/Voucher/TransferCheck',
							{voucherId:vId,userName:uName},
							function(jResult)
								{
									if(jResult.Success=='1' && jResult.Confirm=='1')
										{
											if(confirm(jResult.Message))
												
												{
													$('.btnVoucherTransfer').show();
													$('.voucherToMessageRow').show();
													$('.voucherToMessage').html('Message to '+ uName);
													$(this).hide();
												}
										}
									else
										{
											if(jResult.Success=='1')
												{
													$('.btnVoucherTransfer').show();
													$('.voucherToMessageRow').show();
													$('.voucherToMessage').html('Message to '+ jResult.ToUserFullName);
													$(this).hide();
													alert(jResult.Message);
												}
											else
												{
													alert(jResult.Message);
												}
											
										}
								}
							);
			}
		);
		
		$('.businessCategoryParent').click(function()
			{
				var parentId =$(this).parent().parent().attr('id');
				
				if($('#'+parentId+'>div.businessSubCategoryGroup').is(':visible'))
					{
						$(this).removeClass('toggleOn');
						$(this).addClass('toggleOff');
						$('#'+parentId+'>div.businessSubCategoryGroup').hide();
					}
				else
					{
						$(this).removeClass('toggleOff');
						$(this).addClass('toggleOn');
						$('#'+parentId+'>div.businessSubCategoryGroup').show();
						//$('#'+parentId+'>div.businessSubCategoryGroup>div> span>input[type="checkbox"]').attr('checked','checked');
					}
					
			}
		);
		
		$('.businessCategoryGroup span>input[type="checkbox"]').click(function()
			{
				if($(this).is(':checked'))
					{
						$(this).parent().parent().addClass('selectedVoucherMerchant');
					}
				else
					{
						$(this).parent().parent().removeClass('selectedVoucherMerchant');
					}
				
			}
		);
		
		$('.voucherRedeemSelectColumn>input[type="checkbox"]').click(function()
			{
				if($(this).is(':checked'))
					{
						$('div#'+ $(this).attr('counter')).show();
					}
				else
					{
						$('div#'+ $(this).attr('counter') + '>span>input[type="text"]').val('');
						$('div#'+ $(this).attr('counter')).hide();
					}
			}
		);
		
		
		$('.serchControlOpenCloseLink').click(function()
			{
				if($('.pageListSearchControl').is(':visible'))
					{
						$(this).removeClass('toggleOnRight');
						$(this).addClass('toggleOffRight');
						$('.pageListSearchControl').hide();
					}
				else
					{
						$(this).addClass('toggleOnRight');
						$(this).removeClass('toggleOffRight');
						$('.pageListSearchControl').show();
					}
			}
		);
		
		$('.listColumnHeaderSearchImage').click(function()
			{
				var name = $(this).attr('id');
				var boxName = 'columnSearchBox_'+name.substring(name.indexOf('_') + 1);
				$('.listColumnHeaderSearchBox').hide();
				
				if($('.'+ boxName).is(':visible'))
					{$('.'+ boxName).hide();}
				else
					{$('.'+ boxName).show();}
				
			}
		);
		
		$('.cmbApproveBrand').change(function()
			{
				var selected = $(this).val().toLowerCase();
				var proceed = true;
				var msg;
				var bId  = $('#brandid').val();
				
				if(selected=='false')
					{
						msg = prompt("Reason for failing brand approval:","");
						
						if(msg==null || msg=='')
						{proceed=false;}
					}
				
				if(proceed==true)
					{
						$.getJSON('/Brand/Approve',
							{brandId:bId,status:selected,message:msg},
							function(jResult)
								{
									if(jResult.Success==1 && jResult.ReturnUrl != '')
																		
										{
											window.location.replace(jResult.ReturnUrl);
										}
									else
										{
											alert(jResult.Message);
										}
								}
						);
					}
			}
		);
		
		//Subscription Subscribe button Click
		$('.defaultSubscriptionSubDetailsCostBuy').click(function()
			{
				var prodId = $(this).attr('id');
				$('.cartAreaSpacer').hide();
				$('#divCart').load('/Cart/AddToCart',
					{itemId:prodId,itemType:2, quantity:1  });
			}
		);
		
		//Default config SubGroup)
		$('.defaultSubGroup').change(function()
			{
				var grpId = $(this).val();
				$('.defaultMerchantSubscription').load('/Subscription/SubsCombo?selectname=merchantdefaultsubscription&groupId=' + grpId);
			}
		);
		
		//=======Updating Selling price automatically when changing fees=======
		
		$('.txtNetworkAdminFee').keyup(function(event)
			{
				var adFee = $(this).val();
				var hndFee = $('.txtNetworkHandlingFee').val();
				var perc = $('.txtNetworkMarkupPercentage').val();
				var iId = $('.txtItemId').val();
				var iType = $('.txtItemType').val();
				
				$('.sellingPriceValue').load('/TradeSetting/SellingPrice?itemId='+ iId + '&itemType=' + iType + '&adminFee='+  adFee + '&handlingfee=' + hndFee + '&markUp=' + perc);
			}
		);
		$('.txtNetworkHandlingFee').keyup(function(event)
			{
				var hndFee = $(this).val();
				var adFee = $('.txtNetworkAdminFee').val();
				var perc = $('.txtNetworkMarkupPercentage').val();
				var iId = $('.txtItemId').val();
				var iType = $('.txtItemType').val();
				
				$('.sellingPriceValue').load('/TradeSetting/SellingPrice?itemId='+ iId + '&itemType=' + iType + '&adminFee='+  adFee + '&handlingfee=' + hndFee + '&markUp=' + perc);
			}
		);
		$('.txtNetworkMarkupPercentage').keyup(function(event)
			{
				var perc = $(this).val();
				var adFee = $('.txtNetworkAdminFee').val();
				var hndFee = $('.txtNetworkHandlingFee').val();
				var iId = $('.txtItemId').val();
				var iType = $('.txtItemType').val();
				$('.sellingPriceValue').load('/TradeSetting/SellingPrice?itemId='+ iId + '&itemType=' + iType + '&adminFee='+  adFee + '&handlingfee=' + hndFee + '&markUp=' + perc);
			}
		);
		
		$('.sellingPriceRefresh').click(function()
			{
				var perc = $('.txtNetworkMarkupPercentage').val();
				var adFee = $('.txtNetworkAdminFee').val();
				var hndFee = $('.txtNetworkHandlingFee').val();
				var iId = $('.txtItemId').val();
				var iType = $('.txtItemType').val();
				$('.sellingPriceValue').load('/TradeSetting/SellingPrice?itemId='+ iId + '&itemType=' + iType + '&adminFee='+  adFee + '&handlingfee=' + hndFee + '&markUp=' + perc);
			}
		);
		//=====================================================================
		
		$('#paidascurrency').change(function()
			{
				var vId = $('#id').val();
				var redeemCur =$('#paidascurrency').val();
				var cashIn = $('#cashredeemable').val();
				if (cashIn=='')
					cashIn=0.0;
				
				$('.cashMerchantList').load('/Voucher/CashMerchants?cashInput=' + cashIn + '&redeemCurrency=' + redeemCur + '&vouchcerId=' + vId);
			}
		);
		$('#cashredeemable').keyup(function()
			{
				var vId = $('#id').val();
				var redeemCur =$('#paidascurrency').val();
				var cashIn = $(this).val();
				if (cashIn=='')
					cashIn=0.0;
				
				$('.cashMerchantList').load('/Voucher/CashMerchants?cashInput=' + cashIn + '&redeemCurrency=' + redeemCur + '&vouchcerId=' + vId);
			}
		);
		
		$('#downloadable').click(function()
			{
				if($(this).is(':checked'))
					{
						$('#divDownloadFile').show();//.addclass('dloadShow');
					}
				else
					{
						$('#divDownloadFile').hide();//.addclass('dloadHide');
					}
			}
		);
		
		$('.addDigiProductButton').unbind('click');
		$('.addDigiProductButton').live('click',function()
			{
				appendRow('digiProducts','tblDigitalProducts');
				$('#tblDigitalProducts').show();
			}
		);
    }
);
	  
	  function HtmlEncode(str)
	  {
		var retValue='';
		if(str != null || str != '')
			{
				retValue = str.replace('&lt;','<');
				retValue = str.replace('&gt;','>');
			}
		return retValue;
	  }
		//function ClearCart()
			//{
			//	$('.cartAreaSpacer').hide();
			//	$('#divCart').load('/Cart/clear');
			//	window.location.reload();				
			//}  
			
		function ChangeType(selectname,chosenoption)
			{
				if (chosenoption.value!="nothing")
				{
					AjaxCallChangeType(chosenoption.value,selectname);
				}
			}
        
		function LoadTemplateFields(chosenoption,target)
		   {
			
				if(chosenoption.value!="nothing")
					{
						var tempId = chosenoption.value;
						var verNum =$('#versionnumber').val();
						if(verNum==null)
						{verNum=0;}
						var vName = $('#itemname').val();
	
						$('#' + target).load('/Template/GetTemplateFields',
											{templateId:tempId,viewVersion:verNum,viewName:vName});
						
						if(chosenoption.value==0)
						{
							$('.templateDataAction').hide();
							$('#tDataDiv').hide();
						}
						else
						{
							$('.templateDataAction').show();
							$('#tDataDiv').show();
						}
					}
		   }
		
		
		function LoadSelection(chosenoption,target,tableType)
		   {
				if(chosenoption.value!="nothing")
					{
						AjaxCallLoadItemsTable(chosenoption.value,target,tableType);
					}
		   }
		function AjaxCallLoadItemsTable(itemType,target,tableType)
			{
				var tType;
				switch(tableType)
					{
					case "ds":
                      tType="&tType=2";
                      break;
                    case "viewitem":
                      tType="&tType=1";
                      break;
                    default:
                     tType="&tType=2";
					}
				$('#' + target).load('/Rules/ItemsTableList?itemType=' + itemType + tType);
			}
			
        function AjaxCallResSelect(cell,resType,selectname)
           {$(cell).load('/ContentManagement/ItemsList?itemType=' + resType + '&selectname=' + selectname);}   
            
		function AjaxCallViewItemsCombo(cell,itemType,selectname)
            {$(cell).load('/SiteMenu/ViewItemCombo?itemType=' + itemType + '&selectname=' + selectname);} 
			
		function AjaxCallUserControls(cell,selectname)
            {$(cell).load('/ContentManagement/UcCombo?selectname=' + selectname);} 
		
		function AjaxCallSubGroups(cell,selectname)
			{$(cell).load('/SubscriptionGroup/Groups?selectname=' + selectname);}
			
		function AjaxCallSQLType(cell,selectname)
            {$(cell).load('/Rules/SQLTypeItems?selectname=' + selectname);}

		function AjaxCallInputType(cell,selectname)
            {$(cell).load('/Rules/InputTypeItems?selectname=' + selectname);}
			
			 
        function AjaxCallChangeType(resType,selectname)
            {
			   var tdVal="tdValue_" + selectname.substring(selectname.lastIndexOf('_') + 1);
			 	$('#' + tdVal).load('/ContentManagement/ResourceList?resType=' + resType + "&selectname=" + selectname);
            } 
            
          //=====Table functions====
          function MakeTable(itemDivName,tableName) 
            { 
                row=new Array(); 
                cell=new Array(); 
                val=new Array();
                row_num=1; //edit this value to suit 

                tab=document.createElement('table'); 
                tab.setAttribute('id',tableName); 
                tab.setAttribute('name',tableName); 
                thd=document.createElement('thead');
                switch (itemDivName)
                    {
                    case "itemFields":
                      cell_num=5;
                      val[0]="Name";
                      val[1]="Value";
                      val[2]="Type";
                      val[3]="Data field";
					  val[4]="";
                      break;
                    case "itemCSS":
                      cell_num=3;
                      val[0]="Name";
                      val[1]="Value";
                      val[2]="";
                      break;
                    case "itemScript":
                      cell_num=3;
                      val[0]="Name";
                      val[1]="Value";
                      val[2]="";
                      break;
					case "divExtraFields":
                      cell_num=6;
                      val[0]="Field name";
					  val[1] = "Friendly name";
                      val[2]="Value type";
					  val[3]="Allow nulls";
					  val[4]="Size";
                      val[5]="";
                      break;
					case "divUcs":
                      cell_num=2;
                      val[0]="Select user control";
                      val[1]="";
                      break;
                    case "itemMeta":
                      cell_num=3;
                      val[0]="Name";
                      val[1]="Value";
                      val[2]="";
                      break;
					  case "itemSubs":
                      cell_num=4;
                      val[0]="";
                      val[1]="Menu label";
                      val[2]="Page";
					  val[3]="";
                      break;
					  case "itemTempFields":
                      cell_num=6;
                      val[0]="Field name";
                      val[1]="Friendly name";
                      val[2]="Description";
					  val[3]="Field type";
					  val[4]="Scrap data";
					  val[5]="";
                      break;
					  case "itemSubCat":
                      cell_num=5;
                      val[0]="";
                      val[1]="Name";
                      val[2]="Description";
					  val[3]="Scope";
					  val[4]="";
                      break;
					   case "itemFeatures":
                      cell_num=3;
                      val[0]="Name";
                      val[1]="Value";
                      val[2]="";
                      break;
					  case "itemProdRes":
                      cell_num=5;
                      val[0]="";
                      val[1]="Name";
                      val[2]="Type";
					  val[3]="Is main";
					  val[4]="";
                      break;
					   case "digiProducts":
                      cell_num=4;
                      val[0]="";
                      val[1]="File";
                      val[2]="Change file";
					  val[3]="";
                      break;
					   case "itemSections":
                      cell_num=3;
                      val[0]="Section name";
                      val[1]="Section content";
					  val[2]="";
                      break;
					  case "divTemplateData":
					  cell_num=3;
					  val[0]="Name";
					  val[1]="Value";
					  val[2]="";
					  break;
					  case "voucherGeneralSecurity":
					  cell_num=3;
					  val[0]="Security check";
					  val[1]="Requirements";
					  val[2]="";
					  break;
					  case "voucherCashSecurity":
					  cell_num=3;
					  val[0]="Security check";
					  val[1]="Requirements";
					  val[2]="";
					  break;
					  case "customVoucherSecurity":
					  cell_num=5;
					  val[0]="Check";
					  val[1]="Requirements";
					  val[2]="Type";
					  val[3]="Must pass";
					  val[4]="";
					  break;
					  case "itemRequiredInfo":
					  cell_num=3;
					  val[0]="Required info";
					  val[1]="Data type";
					  val[2]="";
					  break;
					   case "divSubscriptions":
					  cell_num=3;
					  val[0]="Subscription group";
					  val[1]="Display template";
					  val[2]="";
					  break;
                    default:
                     cell_num=1;
                    }
                    
                    for(c=0;c<row_num;c++)
                        { 
                            row[c]=document.createElement('tr'); 
                            for(k=0;k<cell_num;k++) 
                                { 
                                    cell[k]=document.createElement('th'); 
                                    cont=document.createTextNode(val[k]); 
                                    cell[k].appendChild(cont); 
                                    row[c].appendChild(cell[k]); 
                                } 
                            thd.appendChild(row[c]); 
                        } 
                     tab.appendChild(thd); 
                    
                tbo=document.createElement('tbody'); 
                tab.appendChild(tbo); 
                document.getElementById(itemDivName).appendChild(tab); 
                
                return tab;
            } 
            
          // append row to the HTML table
            function appendRow(itemDivName,tableName)
            {
	            var divItems = document.getElementById(itemDivName).childNodes;
	          
	            var tbl;  // table reference
	            for(var y = 0;y< divItems.length;y++)
	                {
	                 if(divItems.item(y).id==tableName)
	                    {
	                        tbl=divItems.item(y);
	                        break;
	                    }
	                }

	            if(tbl==null) 
	                {
	                    tbl = MakeTable(itemDivName,tableName); 
	                }
	                
	            // append table row
	            var row = tbl.insertRow(tbl.rows.length);
	            
				
				//if(tableName=='tblCustomFields')
				//	{
				//		$('#divExtraFields').append('<input type="hidden" name="customfield.Index" value="' + tbl.rows.length + '" />');
				//	}
				
				// insert table cells to the new row
	            for (var i=0; i<tbl.rows[0].cells.length; i++)
	                {
		               //Control fields table
		               if(tableName=='tblFields') 
		                    {
		                        if(i==0)
	                                {
		                                createCell(row.insertCell(i), createTextInput('fieldname_' + tbl.rows.length) , 'tdName_' + tbl.rows.length);
		                            }
		                        if(i==1)
	                                {
		                                 createCell(row.insertCell(i), createTextInput('fieldvalue_' + tbl.rows.length), 'tdValue_' + tbl.rows.length);
		                            }
		                        if(i==2)
	                                {
		                                createCell(row.insertCell(i), createControlTypeSelect('fieldcontroltype_' + tbl.rows.length,1), 'tdCType_' + tbl.rows.length);
		                            }
		                        if(i==3)
	                                {
		                                createCell(row.insertCell(i), TrueFalseSelect("datafield_" + tbl.rows.length), 'tdDataField_' + tbl.rows.length);
		                            }
								if(i==4)
	                                {
		                                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
		                            }
		                    }
		               //CSS fields table   
		               if(tableName=='tblCss') 
		                    {
		                       if(i==0)
	                              {
		                            createCell(row.insertCell(i), createTextInput('cssname_' + tbl.rows.length) , 'tdName_' + tbl.rows.length);
		                          }
		                        if(i==1)
	                                {
		                                AjaxCallResSelect(row.insertCell(i),3,'cssres_'  + tbl.rows.length );
		                            }
		                        if(i==2)
	                                {
		                                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
		                            }
		                       
		                    }
		                    
		                //Scripts fields table   
		               if(tableName=='tblScript') 
		                    {
		                         if(i==0)
	                               {
		                            createCell(row.insertCell(i), createTextInput('scriptname_' + tbl.rows.length) , 'tdName_' + tbl.rows.length);
		                           }
		                        if(i==1)
	                                {
		                                AjaxCallResSelect(row.insertCell(i),1,'scriptres_'  + tbl.rows.length );
		                            }
		                        if(i==2)
	                                {
		                                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
		                            }
		                       
		                    }
		                    
                     //Meta fields table   
		               if(tableName=='tblMeta') 
		                    {
		                         if(i==0)
	                              {
		                            createCell(row.insertCell(i), createTextInput('metaname_' + tbl.rows.length) , 'tdName_' + tbl.rows.length);
		                          }
		                        if(i==1)
	                                {
		                                AjaxCallResSelect(row.insertCell(i),2,'metares_'  + tbl.rows.length );
		                            }
		                        if(i==2)
	                                {
		                                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
		                            }
		                    }
		                
					//Custom fields table   
		               if(tableName=='tblCustomFields') 
		                    {
		                         if(i==0)
	                                {
		                             createCell(row.insertCell(i), createTextInput('customfield[' + tbl.rows.length + '].fieldname') , 'tdName_' + tbl.rows.length);
		                            }
								 if(i==1)
	                                {
		                             createCell(row.insertCell(i), createTextInput('customfield[' + tbl.rows.length + '].friendlyname') , 'tdName_' + tbl.rows.length);
		                            }
		                         if(i==2)
	                                {
		                                AjaxCallSQLType(row.insertCell(i),'customfield['  + tbl.rows.length +'].sqldatatype' );
		                            }
		                         if(i==3)
	                                {
		                                AjaxCallAllowNulls(row.insertCell(i),'customfield['  + tbl.rows.length +'].allownulls','halfSize' );
		                            }
								if(i==4)
	                                {
		                                createCell(row.insertCell(i), createTextInputWithClass('customfield[' + tbl.rows.length + '].fieldsize','quaterSize') , 'tdName_' + tbl.rows.length);
		                            }
								if(i==5)
	                                {
		                                createCell(row.insertCell(i), createLinkImg((tbl.rows.length-2)), 'tdBtn_' + tbl.rows.length);
		                            }
		                    }
					//User controls table
					if(tableName=='tblUcs') 
		                    {
		                        
		                        if(i==0)
	                                {
		                                AjaxCallUserControls(row.insertCell(i),'ucontrol_'  + tbl.rows.length );
		                            }
		                       if(i==1)
	                                {
		                                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
		                            }
		                    }
					//SUb menus table
					if(tableName=='tblSubs') 
		                {
		                        
		                    if(i==0)
	                            {
		                            createCell(row.insertCell(i), CreateLink('','Edit'), 'tdName_' + tbl.rows.length);
		                        }
		                    if(i==1)
	                            {
									createCell(row.insertCell(i), createTextInput('new_label_' + tbl.rows.length), 'tdLabel_' + tbl.rows.length);
		                        }
							if(i==2)
	                            {
									AjaxCallViewItemsCombo(row.insertCell(i),'1','new_link_' + tbl.rows.length)
		                        }
							if(i==3)
	                            {
		                            createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
		                        }			
		                    }

					//Template fields table
					if(tableName=='tblTempFields') 
						{
							if(i==0)
								{
									createCell(row.insertCell(i), createTextInput('new_fieldname_' + tbl.rows.length) , 'tdName_' + tbl.rows.length);
								}
							if(i==1)
								{
								   createCell(row.insertCell(i), createTextInput('new_friendlyname_' + tbl.rows.length), 'tdFName_' + tbl.rows.length);
								}
							if(i==2)
								{
								 createCell(row.insertCell(i), createTextInput('new_description_' + tbl.rows.length), 'tdDescription_' + tbl.rows.length);
								}
							if(i==3)
							   {
							 createCell(row.insertCell(i), createControlTypeSelect('new_controltype_' + tbl.rows.length,0), 'tdCType_' + tbl.rows.length);
							   }
							 if(i==4)
							 {
							 createCell(row.insertCell(i), createTextInput('new_fieldvalue_' + tbl.rows.length), 'tdValue_' + tbl.rows.length);
								}
							if(i==5)
							   {
									createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
							   }
						}

					//Sub category fields table
					if(tableName=='tblSubCat') 
						{
							if(i==0)
								{
									createCell(row.insertCell(i), CreateLink('','Edit'), 'tdEdit_' + tbl.rows.length);
								}
							if(i==1)
								{
								   createCell(row.insertCell(i), createTextInput('new_name_' + tbl.rows.length), 'tdCatName_' + tbl.rows.length);
								}
							if(i==2)
								{
								 createCell(row.insertCell(i), createTextInput('new_description_' + tbl.rows.length), 'tdDescription_' + tbl.rows.length);
								}
							if(i==3)
							   {
							   AjaxCallCategoryScopeSelect(row.insertCell(i),'new_scope_' + tbl.rows.length);
							   }
							if(i==4)
							   {
									createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
							   }
						}	
				
					//Product resources fields table
					if(tableName=='tblProdRes') 
						{
							if(i==0)
								{
									createCell(row.insertCell(i), CreateLink('','Preview'), 'tdPreview_' + tbl.rows.length);
								}
							if(i==1)
								{
								   createCell(row.insertCell(i), createTextInput('fieldvalue_' + tbl.rows.length), 'tdValue_' + tbl.rows.length);
								}
							if(i==2)
								{
								createCell(row.insertCell(i), createControlTypeSelect('fieldcontroltype_' + tbl.rows.length,1), 'tdType_' + tbl.rows.length);
								}
							if(i==3)
							   {
								createCell(row.insertCell(i), createInput('residmain','radio',tbl.rows.length,null), 'tdIsmain_' + tbl.rows.length);
							   }
							if(i==4)
							   {
									createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdResBtn_' + tbl.rows.length);
							   }
						}
	
					//Product featurres fields table   
					if(tableName=='tblFeatures') 
						 {
							if(i==0)
								{
								 createCell(row.insertCell(i), createTextInput('featurename_' + tbl.rows.length) , 'tdName_' + tbl.rows.length);
								}
								if(i==1)
								{
								 createCell(row.insertCell(i), createTextInput('featurevalue_' + tbl.rows.length) , 'tdFValue_' + tbl.rows.length);
								}
								if(i==2)
								{
								   createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdFetBtn_' + tbl.rows.length);
								}
						 }
						 
	
					//Downloadable products table
					if(tableName=='tblDigitalProducts') 
										{
												
											if(i==0)
												{
													createCell(row.insertCell(i), CreateLink('','Preview'), 'tdFilePreview_' + tbl.rows.length);
												}
											if(i==1)
												{
												
									createCell(row.insertCell(i), createInput('downloadfile_' + tbl.rows.length,'file','',null), 'tdFileName_' + tbl.rows.length);
												}
											if(i==2)
												{
												var params = [ 
																{ 
																   "Name":"onclick", 
																   "Value":"LoadDialog(this)" 
																}
															];
				createCell(row.insertCell(i), createInput('btnchangefile_' + tbl.rows.length,'button','Change file',params), 'tdFileChange_' + tbl.rows.length);
												}
											if(i==3)
												{
													createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdFileBtn_' + tbl.rows.length);
												}			
											}
							
	//Master sections table   
	if(tableName=='tblSections') 
	    {
	        if(i==0)
	            {
	                createCell(row.insertCell(i), createTextInput('sectionname_' + tbl.rows.length) , 'tdSectionName_' + tbl.rows.length);
	            }
	        if(i==1)
	            {
					AjaxCallUserControls(row.insertCell(i),'sectionucid_'  + tbl.rows.length );
	            }
	        if(i==2)
	            {
	                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
	            }
        }
		
		//Template data items table
		if(tableName=='tblTemplateData')				
		{
				if(i==0)
	            {
	                createCell(row.insertCell(i), createTextInput('tempdataitemname_' + tbl.rows.length) , 'tdtempdataitemname_' + tbl.rows.length);
	            }
				if(i==1)
	            {
	                createCell(row.insertCell(i), createTextInput('tempdataitemvalue_' + tbl.rows.length) , 'tdtempdataitemvalue_' + tbl.rows.length);
	            }
				 if(i==2)
	            {
	                createCell(row.insertCell(i), createLinkImg(tbl.rows.length), 'tdBtn_' + tbl.rows.length);
	            }
		}
		//Voucher General security defaults
		if(tableName=='tblGeneralSecurity')
		{
			if(i==0)
			{
				createCell(row.insertCell(i), createTextInput('vouchergeneraldefaultsecurity_name[' + tbl.rows.length + ']') , '');
			}
			if(i==1)
			{
				createCell(row.insertCell(i), createTextInput('vouchergeneraldefaultsecurity_value[' + tbl.rows.length + ']') , '');
			}
			if(i==2)
			{
				createCell(row.insertCell(i), createLinkImg(tbl.rows.length), '');
			}
		}
		
		//Voucher cash security defaults
		if(tableName=='tblCashSecurity')
		{
			if(i==0)
			{
				createCell(row.insertCell(i), createTextInput('vouchercashdefaultsecurity_name[' + tbl.rows.length + ']') , '');
			}
			if(i==1)
			{
				createCell(row.insertCell(i), createTextInput('vouchercashdefaultsecurity_value[' + tbl.rows.length + ']') , '');
			}
			if(i==2)
			{
				createCell(row.insertCell(i), createLinkImg(tbl.rows.length), '');
			}
		}
		
		//Voucher custom security settings
		if(tableName=='tblCustomVoucherSecurity')
		{
			if(i==0)
			{
				createCell(row.insertCell(i), createTextInput('custom_name[' + tbl.rows.length + ']') , '');
			}
			if(i==1)
			{
				createCell(row.insertCell(i), createTextInput('custom_value[' + tbl.rows.length + ']') , '');
			}
			
			if(i==2)
			{
				AjaxCallVoucherSecType(row.insertCell(i),'custom_type[' + tbl.rows.length + ']');
				
			}
			if(i==3)
			{
				CheckBox(row.insertCell(i),'custom_mustpass[' + tbl.rows.length + ']','',true);
			}
			if(i==4)
			{
				createCell(row.insertCell(i), createLinkImg(tbl.rows.length), '');
			}
		}
		
		//Subscription required information
		if(tableName=='tblRequiredInfo')
		{
			if(i==0)
			{
				createCell(row.insertCell(i), createTextInput('requiredinfoname_' + tbl.rows.length) , '');
			}
			if(i==1)
			{
			    AjaxCallInputType(row.insertCell(i),'requiredinfotype_'  + tbl.rows.length);
			}
			if(i==2)
			{
				createCell(row.insertCell(i), createLinkImg(tbl.rows.length), '');
			}
		}
		//Subscriptions
		if(tableName=='tblSubscriptions')
		{
			if(i==0)
			{
				AjaxCallSubGroups(row.insertCell(i),'subgroup_' + tbl.rows.length);
			}
			if(i==1)
			{
			    AjaxCallUserControls(row.insertCell(i),'displaytemplate_'  + tbl.rows.length);
			}
			if(i==2)
			{
				createCell(row.insertCell(i), createLinkImg(tbl.rows.length), '');
			}
		}
		
	}
	   $('#' + itemDivName).parent().addClass('productFormTable');
 }

        // append inner control to cell t
       function createCell(cell, text, id)
                {
                cell.setAttribute('id', id);    
	            cell.appendChild(text);                   
            }

        // delete table rows with index greater then 0
       function deleteRows(img)
            {
				//var delRow = img.parentNode.parentNode;
				//var tbl = delRow.parentNode.parentNode;//delRow.parentElement;
				//var rIndex = Number(delRow.sectionRowIndex);
				//tbl.deleteRow(rIndex);
				//var tableName = $(tbl.parentElement).attr('id');
				//var rowCount = $('#' + tableName + ' tr').size();
				//var item ='#' + img.id;
				//alert(item);
				//var rowCount = $('#' + tableName + ' tr').size();
				//if(rowCount < 2)
				//{
				//	$('#' + tableName).remove();
				//	$('#' + 'btn_' + tableName).addClass('addBtn form_btn') 
				//}
				//else
				//{
					
				//	$(item).parent().parent().remove(); 
				//}
				//alert('called');
            }
		
		function LoadDialog(target)
		{
			var targetRowNum = target.id.substring(target.id.lastIndexOf('_') + 1);
			var id = 'tdFileName_' + targetRowNum;
			var cell =document.getElementById(id);
			if (cell!=null)
				{
					cell.innerHTML='';
					cell.appendChild(createInput('downloadfile_' + targetRowNum,'file',null));
				}
				var prevCell = document.getElementById('tdFilePreview_' + targetRowNum)
			if (prevCell!=null)
				{
					prevCell.innerHTML='';
				}	
		}
		
		function AjaxCallDeleteTemplateField(fieldId)
            {
                var id = (Number(fieldId));
				$.get('/Template/DeleteField',
					{id:id},function(data)
							{
								alert(data);
							}
					);
			}
		// delete table row and item from db
       function deleteRowsAndItem(img,fieldId)
            {
	            var rowNum = (Number(img.id)-2);
	            var tbl =img.parentElement.parentElement.parentElement;
	          //Delete item from db
			  if(confirm('Field will be deleted permanently'))
				 {
				 AjaxCallDeleteTemplateField(fieldId);
				// delete row
				tbl.deleteRow(rowNum);
				}
						 
            }
        function createTextInput(id)
            {
                var input = document.createElement('input');
                input.setAttribute('id',id);
                input.setAttribute('name',id);
                input.setAttribute('type','text');
                return input;
            }
         function createTextInputWithClass(id,strClass)
			{
				 var input = document.createElement('input');
                input.setAttribute('id',id);
                input.setAttribute('name',id);
				input.setAttribute('class',strClass);
                input.setAttribute('type','text');
				return input;
			}
         function createLinkImg(id)
            {
                var img = document.createElement('img');
                img.setAttribute('id',id);
                img.setAttribute('alt','Delete row');
				img.setAttribute('title','Delete item');
				img.setAttribute('class','btnDelete');
                img.setAttribute('src','/Content/Images/cross.png');
 				//img.setAttribute('onclick','deleteRows(this)');
				//alert($(img).attr('class'));
                return img;
            }
			
			function AjaxCallCategoryScopeSelect(cell,selectName)
            {$(cell).load('/Category/CategoryScope?selectname='  + selectName);}
			
			function AjaxCallMimeTypesSelect(cell,selectName)
            {$(cell).load('/Products/MimeTypesCombo?selectname='  + selectName); }
			
			function AjaxCallVoucherSecType(cell,selectName)
			{$(cell).load('/Voucher/SecurityType?selectname='  + selectName);}
		
		function createInput(id,type,value,params)
			{
				var input = document.createElement('input');
                input.setAttribute('id',id);
                input.setAttribute('name',id);
				input.setAttribute('type',type);
				input.setAttribute('value',value);
				if(params!=null)
					{
						for (var i = 0; i < params.length; i++) 
							{ 
								input.setAttribute(params[i].Name,params[i].Value);
							} 
					}
				return input;
			}
         function createControlTypeSelect(id,addEvent)
            {
                var select = document.createElement('select');
                select.setAttribute('id',id);
                select.setAttribute('name',id);
				if(addEvent==1)
					{
					select.setAttribute('onchange','ChangeType(this.name,this)');
					}
                var options = new Array();
                options[0] = "Text";
                options[1] = "Image";
                options[2] = "Audio";
                options[3] = "Video";
                options[4] = "Document";
				options[5] = "Flash";
                
                for (var i=0; i<options.length; i++)
                    {
                        var option =document.createElement('option');
                        option.setAttribute('value',i + 1);
                        option.innerHTML = options[i];
                        select.appendChild(option);
                    }
                return select;
            }
			function AjaxCallAllowNulls(cell,selectname,cls)
            {
				$(cell).append(TrueFalseWIthDefault(selectname,'True',cls));
			}
		function YesNoSelect(id)
			{
				 var select = document.createElement('select');
                select.setAttribute('id',id);
                select.setAttribute('name',id);
				
				 var options = new Array();
                options[0] = "No";
                options[1] = "Yes";
				for (var i=0; i<options.length; i++)
                    {
                        var option =document.createElement('option');
                        option.setAttribute('value',i + 1);
                        option.innerHTML = options[i];
                        select.appendChild(option);
                    }
                return select;
			}
			function TrueFalseSelect(id)
			{
				 var select = document.createElement('select');
                select.setAttribute('id',id);
                select.setAttribute('name',id);
	
                        var option1 =document.createElement('option');
                        option1.setAttribute('value','False');
                        option1.innerHTML = 'False';
                        select.appendChild(option1);
						
						var option2 =document.createElement('option');
                        option2.setAttribute('value','True');
                        option2.innerHTML = 'True';
                        select.appendChild(option2);
                    
                return select;
			}
			
		function TrueFalseWIthDefault(id,def,cls)
			{
				var select = document.createElement('select');
                select.setAttribute('id',id);
                select.setAttribute('name',id);
				select.setAttribute('class',cls);
		
                        var option1 =document.createElement('option');
                        option1.setAttribute('value','False');
						if('false'==def.toLowerCase())
							{
								option1.setAttribute('selected','selected');
							}
                        option1.innerHTML = 'False';
                        select.appendChild(option1);
						
						var option2 =document.createElement('option');
                        option2.setAttribute('value','True');
						if('true'==def.toLowerCase())
							{
								option2.setAttribute('selected','selected');
							}
                        option2.innerHTML = 'True';
                        select.appendChild(option2);

                return select;
			}

			function HideShow(which)
				{
					var dv = document.getElementById(which);
					if (dv==null)
					return
					if (dv.style.display=="block")
					dv.style.display="none"
					else
					dv.style.display="block"
				}
			function CreateLink(href,label)
				{
					var link = document.createElement('a');
					link.setAttribute('href',href);
					return link;
				}
				
			
			//function ToggleDivVisibility(target,chk)
			//	{
			//		var dv =document.getElementById(target);
			//		if (dv!=null)
			//			{
			//				if (chk.checked == 1)
			//					{
			//						 dv.setAttribute("class", "dloadShow"); 
			//						 dv.setAttribute("className", "dloadShow");
			//					}
			//				else
			//					{
			//						 dv.setAttribute("class", "dloadHide"); 
			//						 dv.setAttribute("className", "dloadHide");
			//					}
			//			}
			//	}
			
				
			function CheckBox(cell,id,className,checked)
			{
				 var input = document.createElement('input');
                input.setAttribute('id',id);
                input.setAttribute('name',id);
				input.setAttribute('class',className);
                input.setAttribute('type','checkbox');
				if(checked==true)
				{input.setAttribute('checked','checked');}
				$(cell).append(input);
				
				
			}
