function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 
//**********************************************************************************
//**********************************************************************************
function checkboxAction(elem, UrlVal,CurrentOrder){

	var CategoryCount = elem.parentNode.parentNode.parentNode.parentNode.parentNode.childNodes.length;
	//var headerElementCount = elem.parentNode.parentNode.parentNode.parentNode.childNodes[0].childNodes[0].childNodes.length;
	//var headerElements = elem.parentNode.parentNode.parentNode.parentNode.childNodes[0].childNodes[0];
	//var ElementID = headerElements.childNodes[headerElementCount-1].id;
	var SelectedProduct = elem.id.replace('-','_');
	var DivContent = $('#ItemList').html();

	 if(elem.checked){
		elem.parentNode.parentNode.className = "selected";
		//$('#'+ElementID).show();
		var SelectedProductPackage = new Array();
		SelectedProductPackage['ProductCode'] = SelectedProduct;
		SelectedProductPackage['Url'] = UrlVal;
		$('#OrderSummaryDiv').show();
		CurrentOrder.push(SelectedProductPackage);
		$('#'+elem.id).parent().append("<input type='hidden' id='DataURL_"+indexOfProductCode(SelectedProduct,CurrentOrder)+"' name='"+SelectedProduct+"_URL' value='"+UrlVal+"'>");
	}else {
		CurrentOrder = remove_item(elem, CurrentOrder);
	}
	DivContent = PrintSummary(CurrentOrder,ProductList);
	$('#ItemList').html(DivContent);
	
	return CurrentOrder;

}
//************************************************************************************
//************************************************************************************
function radioAction(elem, Package, CurrentOrder){

	var SelectedProduct = elem.id.replace('-','_');
	var DivContent = $('#ItemList').html();
	var CatagoryPrefix;
	if(elem.checked){
			//alert(elem.id.substring(0,elem.id.lastIndexOf('-')));
		for (var k=0; k<CurrentOrder.length; k++) {
			
			CatagoryPrefix = elem.id.substring(0,elem.id.lastIndexOf('-'));
			if (CurrentOrder[k]['ProductCode'].match(CatagoryPrefix+'_')) {
				CurrentOrder.splice(k,1);
				$('#DataURL_'+k).remove();
				$('#DataTitle_'+k).remove();
				$('#DataDesc_'+k).remove();
			}
		}
		var tableNode = elem.parentNode.parentNode.parentNode;
		var totalNodes = tableNode.childNodes.length;
		for (var i=0; i<totalNodes;i++) {
			tableNode.childNodes[i].className="";
		}
		elem.parentNode.parentNode.className = "selected";
		if (SelectedProduct != (CatagoryPrefix+'_None')){
			var SelectedProductPackage = new Array();
			SelectedProductPackage['ProductCode'] = SelectedProduct;
			SelectedProductPackage['Url'] = Package['Url'];
			SelectedProductPackage['Title'] = Package['Title'];
			SelectedProductPackage['Description'] = Package['Description'];
			$('#OrderSummaryDiv').show();
			CurrentOrder.push(SelectedProductPackage);
			
			var indexofProdCode = indexOfProductCode(SelectedProduct,CurrentOrder);
			$('#'+elem.id).parent().append("<input type='hidden' id='DataURL_"+indexofProdCode+"' name='"+SelectedProduct+"_URL' value='"+Package['Url']+"'>");
			$('#'+elem.id).parent().append("<input type='hidden' id='DataTitle_"+indexofProdCode+"' name='"+SelectedProduct+"_Title' value='"+Package['Title']+"'>");
			$('#'+elem.id).parent().append("<input type='hidden' id='DataDesc_"+indexofProdCode+"' name='"+SelectedProduct+"_Description' value=\""+Package['Description']+"\">");
			$('#DataURL_'+indexofProdCode).val(Package['Url']);
			$('#DataTitle_'+indexofProdCode).val(Package['Title']);
			$('#DataDesc_'+indexofProdCode).val(Package['Description']);
			//$('#TotalCol_2').show();
		}
		
	}else {
		elem.parentNode.parentNode.className = "";
	
	}
	//alert(dump(CurrentOrder));
	DivContent = PrintSummary(CurrentOrder,ProductList);
	$('#ItemList').html(DivContent);
	return CurrentOrder;

}
//************************************************************************************
//************************************************************************************
function checkLength(o,n,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		//o.addClass('ui-state-error');
		//updateTips("Length of " + n + " must be between "+min+" and "+max+".");
		return false;
	} else {
		return true;
	}
}

//************************************************************************************
//************************************************************************************
function CalcTotal (CurrentOrder,ProductList) {
	var Total= 0;
	for (var i=0; i<CurrentOrder.length; i++) {
		Total += parseFloat(ProductList[CurrentOrder[i]['ProductCode']]['price']);
	
	}
	return Total;
}
//************************************************************************************
function issetElem (Elem) {

	if (Elem.val().length <= 0 ) {
		Elem.addClass('ui-state-error');
		return false;
	}else {
		Elem.removeClass('ui-state-error');
		return true;
	}
}
//************************************************************************************
function ResetElemError (Elem) {
	Elem.removeClass('ui-state-error');
}
//************************************************************************************
function ValidUrl (url) {
	var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
	if (!v.test(url.val())) {
		url.addClass('ui-state-error');
        return false;
    }else {
		url.removeClass('ui-state-error');
		return true;
	}
	
}
//************************************************************************************
//************************************************************************************
function PrintSummary (CurrentOrder,ProductList) {
	var html = "";
	var inputfields = $('input.inputFields');

	if (CurrentOrder.length==0) {
		$('#OrderSummaryDiv').hide();
		inputfields.each(function(){
			this.disabled = 1;
		});
	}else {
		for (var i=0;i<CurrentOrder.length;i++) {
			html+= "<tr>";
			if (CurrentOrder[i]['Title'] != undefined) {
				html+= "<td>"+ProductList[CurrentOrder[i]['ProductCode']]['name']+"<br><a href=\"";
				html+= CurrentOrder[i]['Url']+"\ class=TitleLink target=_blank>"+CurrentOrder[i]['Title']+"</a></td>";
				html+= "<td>$"+ProductList[CurrentOrder[i]['ProductCode']]['price'];
				html+=".00<br><a class='EditLinkCheckBox "+CurrentOrder[i]['ProductCode']+"' id='EditLinkCheckBox'>Edit</a></td></tr>";
			}else {
				html+= "<td>"+ProductList[CurrentOrder[i]['ProductCode']]['name']+"<br><a href="+CurrentOrder[i]['Url'];
				html+= " target=_blank  class=TitleLink  rel=nofollow>"+CurrentOrder[i]['Url']+"</a></td>";
				html+= "<td>$"+ProductList[CurrentOrder[i]['ProductCode']]['price'];
				html+= ".00<br><a class='EditLinkRadio "+CurrentOrder[i]['ProductCode']+"' id='EditLinkRadio'>Edit</a></td></tr>";
			}

		}
		inputfields.each(function(){
			this.disabled = 0;
		});

		
	}
	html +="<tr class=TotalRow><td>Total:</td><td>$"+CalcTotal(CurrentOrder,ProductList)+".00</td></tr>";
	//alert (CalcTotal(CurrentOrder,ProductList));
	return html;
}
//************************************************************************************
//************************************************************************************
function IsNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

//************************************************************************************
function EditUrlDialogBox (id,CurrentOrder) {
	var Save = 0;
		$("#AddUrlDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			height: 260,
			width: 350,
			modal: true,
			buttons: {
				'Save': function() {
					var bValid = true;
					//allFields.removeClass('ui-state-error');
					bValid = ValidUrl($('#Url'));
					if (bValid) {
						CurrentOrder[id]['Url'] = $('#Url').val();
						var DivContent = PrintSummary(CurrentOrder,ProductList);
						$('#ItemList').html(DivContent);
						$('#DataURL_'+id).val($('#Url').val());
						PrintSummary(CurrentOrder,ProductList);
						Save = 1;
						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				//allFields.val('').removeClass('ui-state-error');
				$(this).dialog('destroy');
			}
		});
		$('#AddUrlDialog').dialog('open');
		EnableEnterKey ('AddUrlDialog');
	return CurrentOrder;
}
//************************************************************************************
function UrlDialogBox (elem,CurrentOrder) {
	var elem2 = elem;
	var Save = 0;
		$("#AddUrlDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			height: 260,
			width: 350,
			modal: true,
			buttons: {
				'Save': function() {
					var bValid = true;
					//allFields.removeClass('ui-state-error');
					bValid = ValidUrl($('#Url'));
					if (bValid) {

						CurrentOrder = checkboxAction(elem2,$('#Url').val(),CurrentOrder);

						Save = 1;
						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				//allFields.val('').removeClass('ui-state-error');
				if (!Save) {
					elem.checked = 0;
				}
				$(this).dialog('destroy');
			}
		});
		if (elem2.checked){
			$('#AddUrlDialog').dialog('open');
		}
		EnableEnterKey ('AddUrlDialog');
		 
	return CurrentOrder;
}
//************************************************************************************
function NoSelectionDialogBox () {
		$("#Pickaproduct").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			height: 160,
			width: 300,
			modal: true,
			buttons: {
				'Ok': function() {

						$(this).dialog('close');
					}
				}
			
		});
		$('#Pickaproduct').dialog('open');
}
//************************************************************************************
function EnableEnterKey (PopUpId) {
	$(document).keypress(function(e) {
		if ((e.which && e.which == 13) || (e.keyCode &&e.keyCode == 13)) {
			if ($('#'+PopUpId).dialog('isOpen')) {
				$('[aria-labelledby$='+PopUpId+']').find(":button:contains('Save')").click();
			}
			return false;
		}
	});
}
//************************************************************************************
function textCounter(field,cntfield,maxlimit) {
	if (cntfield!=undefined){
		//alert (field.val().length);
		if (field.val().length > maxlimit) {
			// if too long...trim it!
			field.val(field.val().substring(0, maxlimit)); 
			//alert(maxlimit);
		}
		// otherwise, update 'characters left' counter
		else
			cntfield.val(maxlimit - field.val().length);
	}
}
//************************************************************************************
//************************************************************************************
function EditBizOppBox (id,CurrentOrder) {
	//var elem2 = elem;
	var ThisPackage = CurrentOrder[id];
	var PackageType = ThisPackage['ProductCode'].substring((ThisPackage['ProductCode'].lastIndexOf('_')+1),ThisPackage['ProductCode'].length);
	var PopUpHeight = 0;
	var MaxDesc = 0;
	if (PackageType == 'R') {
		MaxDesc = 200;
	}else if (PackageType == 'P' ) {
		MaxDesc = 100;
	}else {
		MaxDesc = 0;
	}
	//var MaxDesc ;
	if  (IsNumeric(PackageType)) {
		$('#BO-DescriptionLabel').hide();
		$('.BO-DescCounterDisplay100').hide();
		$('.BO-DescCounterDisplay200').hide();
		$('#BO-Description100').hide();
		$('#BO-Description200').hide();
		PopUpHeight = 300;
	}else {
		$('#BO-DescriptionLabel').show();
		$('#BO-DescCounterDisplay').show();
		$('#BO-Description').hide();
		
		if (MaxDesc == 100 ) {
			$('#BO-Description100').val(ThisPackage['Description']);
			$('#BO-Title').val(ThisPackage['Title']);
			$('#BO-Url').val(ThisPackage['Url']);
			$('#BO-Description100').show();
			$('.BO-DescCounterDisplay100').show();
			$('#BO-Description200').hide();
			$('.BO-DescCounterDisplay200').hide();
		}else if (MaxDesc == 200){
			$('#BO-Description200').show();
			$('.BO-DescCounterDisplay200').show();
			$("#BO-Description100").hide();
			$('.BO-DescCounterDisplay100').hide();
		}
		PopUpHeight = 420;
	}
	jQuery(function($){
		$("#BO-Description200.TextBox200").dodosTextCounter(200, {counterDisplayClass: "BO-DescCounterDisplay200",addLineBreak:true});
		$("#BO-Description100.TextBox100").dodosTextCounter(100, {counterDisplayClass: "BO-DescCounterDisplay100",addLineBreak:true});
	});

	var Save = 0;
		$("#BO_Dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			height: PopUpHeight,
			width: 360,
			modal: true,
			buttons: {
				'Save': function() {
					var bValid = true;
					if (MaxDesc == 0) {
						bValid = issetElem($('#BO-Title')) && bValid ; 
						bValid =  ValidUrl($('#BO-Url')) && bValid  ;
					}else if (MaxDesc == 100 ) {
						bValid = issetElem($('#BO-Title')) && bValid ; 
						bValid =  ValidUrl($('#BO-Url')) && bValid  ;
						bValid = issetElem($('#BO-Description100.TextBox100')) && bValid;
					}else if (MaxDesc == 200) {
						bValid = issetElem($('#BO-Title')) && bValid ; 
						bValid =  ValidUrl($('#BO-Url')) && bValid  ;
						bValid = issetElem($('#BO-Description200.TextBox200')) && bValid;					
					}
					if (bValid) {
						var Package = new Array();
						Package['Url'] = $('#BO-Url').val();
						Package['Title'] = $('#BO-Title').val();
						if (MaxDesc == 200) {
							Package['Description'] = $('#BO-Description200.TextBox200').val();
						}else if (MaxDesc == 100) {
							Package['Description'] = $('#BO-Description100.TextBox100').val();
						}
						$('#BO-Description').val('');
						CurrentOrder[id]['Url']= Package['Url'];
						CurrentOrder[id]['Title']= Package['Title'];
						CurrentOrder[id]['Description']= Package['Description'];
						$('#DataURL_'+id).val(Package['Url']);
						$('#DataTitle_'+id).val(Package['Title']);
						$('#DataDesc_'+id).val(Package['Description']);
						
						var DivContent = PrintSummary(CurrentOrder,ProductList);
						$('#ItemList').html(DivContent);
						PrintSummary(CurrentOrder,ProductList);
						
						Save = 1;
						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {

				if (!Save) {
					ResetElemError($('#BO-Description200.TextBox200'));
					ResetElemError($('#BO-Description100.TextBox100'));
					ResetElemError($('#BO-Title'));
					ResetElemError($('#BO-Url'));
					$('#BO-Url').val('');
					$('#BO-Title').val('');
					$('#BO-Description').val('');
				}
				$(this).dialog('destroy');
			}
		});
		$('#BO_Dialog').dialog('open');
		EnableEnterKey ('BO_Dialog');
	return CurrentOrder;
}
//************************************************************************************
function BizOppBox (elem,CurrentOrder) {
	var elem2 = elem;
	var PackageType = elem.id.substring((elem.id.lastIndexOf('-')+1),elem.id.length);
	var PopUpHeight = 0;
	var MaxDesc ;

	if (PackageType == 'R') {
		MaxDesc = 200;
	}else if (PackageType == 'P' ) {
		MaxDesc = 100;
	}else {
		MaxDesc = 0;
	}
	if  (IsNumeric(PackageType)) {
		$('#BO-DescriptionLabel').hide();
		$('.BO-DescCounterDisplay100').hide();
		$('.BO-DescCounterDisplay200').hide();
		$('#BO-Description100').hide();
		$('#BO-Description200').hide();
		PopUpHeight = 300;
	}else {
		$('#BO-DescriptionLabel').show();
		$('#BO-DescCounterDisplay').show();
		$('#BO-Description').hide();
		
		if (MaxDesc == 100 ) {
			$('#BO-Description100').show();
			$('.BO-DescCounterDisplay100').show();
			$('#BO-Description200').hide();
			$('.BO-DescCounterDisplay200').hide();
		}else if (MaxDesc == 200){
			$('#BO-Description200').show();
			$('.BO-DescCounterDisplay200').show();
			$("#BO-Description100").hide();
			$('.BO-DescCounterDisplay100').hide();
		}
		PopUpHeight = 420;
	}
	jQuery(function($){
		$("#BO-Description200.TextBox200").dodosTextCounter(200, {counterDisplayClass: "BO-DescCounterDisplay200",addLineBreak:true});
		$("#BO-Description100.TextBox100").dodosTextCounter(100, {counterDisplayClass: "BO-DescCounterDisplay100",addLineBreak:true});
	});

	var Save = 0;
		$("#BO_Dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			height: PopUpHeight,
			width: 360,
			modal: true,
			buttons: {
				'Save': function() {
					var bValid = true;
					if (MaxDesc == 0) {
						bValid = issetElem($('#BO-Title')) && bValid ; 
						bValid =  ValidUrl($('#BO-Url')) && bValid  ;
						
					}else if (MaxDesc == 100 ) {
						bValid = issetElem($('#BO-Title')) && bValid ; 
						bValid =  ValidUrl($('#BO-Url')) && bValid  ;
						bValid = issetElem($('#BO-Description100.TextBox100')) && bValid;
					}else if (MaxDesc == 200) {
						bValid = issetElem($('#BO-Title')) && bValid ; 
						bValid =  ValidUrl($('#BO-Url')) && bValid  ;
						bValid = issetElem($('#BO-Description200.TextBox200')) && bValid;					
					}
					if (bValid) {
						var Package = new Array();
						Package['Url'] = $('#BO-Url').val();
						Package['Title'] = $('#BO-Title').val();
						if (MaxDesc == 200) {
							Package['Description'] = $('#BO-Description200.TextBox200').val();
						}else if (MaxDesc == 100) {
							Package['Description'] = $('#BO-Description100.TextBox100').val();
						}
						$('#BO-Description').val('');
						CurrentOrder = radioAction(elem2,Package,CurrentOrder);
						
						Save = 1;
						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				if (!Save) {
					elem.checked = 0;
					for (var k=0; k<CurrentOrder.length; k++) {
						CatagoryPrefix = elem.id.substring(0,elem.id.lastIndexOf('-'));
						if (CurrentOrder[k]['ProductCode'].match(CatagoryPrefix+'_')) {
							var key;
							key = CurrentOrder[k]['ProductCode'].replace('_','-');
							document.getElementById(key).checked=1;
						}
					}
					$('#BO-Url').val('');
					$('#BO-Title').val('');
					$('#BO-Description').val('');
					ResetElemError($('#BO-Description200.TextBox200'));
					ResetElemError($('#BO-Description100.TextBox100'));
					ResetElemError($('#BO-Title'));
					ResetElemError($('#BO-Url'));
				}
				$(this).dialog('destroy');
			}
		});
		if (elem2.checked){
			$('#BO_Dialog').dialog('open');
		}
		EnableEnterKey ('BO_Dialog');

		return CurrentOrder;
}
//************************************************************************************
function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
} 
//************************************************************************************
function startDetecting(){
	var TableTop = $('#MainAdProductsTable').offset().top;
	var TableBottom = $('#MainAdProductsTable').height() + TableTop + 100; 
	$(window).scroll(function()
	{
		var MinTop = $(window).scrollTop();
			if (MinTop> TableTop && MinTop <TableBottom) {
				$('#OrderSummaryDiv').animate({
					top:$(window).scrollTop()+5+"px" 
					},{queue: false, duration: 350});
				}

	});

}

//************************************************************************************
//************************************************************************************

function remove_item(elem,CurrentOrder){
	var key = elem.id.replace('-','_');
	var DivContent = $('#ItemList').html();
	var index = indexOfProductCode(key,CurrentOrder);
	
	if (index!=-1) {
		CurrentOrder.splice(index,1);
		$('#DataURL_'+index).remove();
		DivContent = PrintSummary(CurrentOrder,ProductList);
		elem.parentNode.parentNode.className = "";
		$('#ItemList').html(DivContent);
	}
	if (CurrentOrder.length==0) {
		$('#OrderSummaryDiv').hide();
	}
	//load_array();
	return CurrentOrder;
}//ends remove_item function
//************************************************************************************
function indexOfProductCode (key, CurrentOrder) {
	var index = -1;
	for (var i=0; i<CurrentOrder.length; i++) {
		if (CurrentOrder[i]['ProductCode']==key) {
			index = i;
		}
	}
	return index;
}
//************************************************************************************
//************************************************************************************

//************************************************************************************
$(document).ready(function () {
	recaptchaCreate();
	startDetecting();
	document.onkeypress = stopRKey; 
	$('#EditLinkCheckBox').live('click',function() {
		var ElemId = new Array();
		ElemId = this.className.split(' ');
		var eid = indexOfProductCode(ElemId[ElemId.length-1],CurrentOrder);
		EditBizOppBox(eid,CurrentOrder);
	});
	$('#EditLinkRadio').live('click',function() {
		var ElemId = new Array();
		ElemId = this.className.split(' ');
		var eid = indexOfProductCode(ElemId[ElemId.length-1],CurrentOrder);
		EditUrlDialogBox(eid,CurrentOrder);
	});

	var boxes = $("input.formcheckbox");
	var radios = $("input.formradio");
	


	//***************************Radio Buttons***************************************

	radios.each(function(){

		var classnames = this.className;
		var i;
		classnames = classnames.split(' ');
		for (k=0; k<classnames.length;k++)
		{
			if (classnames[k].match(/box_(\d+)/)){
				pieces = classnames[k].split('_');
				i = parseInt(pieces[1]);
				this.checked=0;
				this.disabled=false;
			}
		}
		$(this).click(function() {
		if (this.checked) {
			if (this.id.match('-None')){
				var Package = new Array();
				Package['Url'] = '';
				Package['Title'] = '';
				Package['Description'] = '';
				CurrentOrder = radioAction(this,Package,CurrentOrder);
				
			}else {

				CurrentOrder = BizOppBox(this,CurrentOrder);
			}
			
		}
			//radioAction(this,i);

		});
		//radioAction(this, i);


	});

	//***************************Check Boxes***************************************
	boxes.each(function(){

		var classnames = this.className;
		var i;
		
		classnames = classnames.split(' ');
		for(c=0;c<classnames.length;c++){
			if(classnames[c].match(/box_(\d+)/)){
				pieces = classnames[c].split('_');
				i = parseInt(pieces[1]);
				this.checked=0;
				this.disabled=false;

			}
		}

		$(this).click(function() {

			if (this.checked) {
				CurrentOrder = UrlDialogBox(this,CurrentOrder);
			}else if (!this.checked) {
				CurrentOrder = remove_item(this,CurrentOrder);
			}

			

		});
	});
//*******************************************************************************
	ValidateForm(CurrentOrder);
});
