$(document).ready(function()
    {
		admarvel_table_sort();
	}
);

function admarvel_table_sort()
{
	//define a parser
	$.tablesorter.addParser({
		// set a unique id
		id: 'formattedNumbers',
		is: function(s){
			// return false so this parser is not auto detected
			return false;
		},
		format: function(s){
		// format your data for normalization
			return s.replace(/,/g, '').replace(/%/g, ''); //removes comma separator from formatted numbers
			
		},
		// set type, either numeric or text
		type: 'numeric'
	});

	$.tablesorter.addParser({
	        // set a unique id
	        id: 'formattedDates',
	        is: function(s) {
	        	// return false so this parser is not auto detected
	            return false;
	        }, //need to make more generic method
	        format: function(s) {
	        	var a = s.split('/');
		        if(a.length==2)//for monthly date format
		        {
		        	s= a[0]+"/01/"+a[1];
		        }
		        else
		        {
		        	a = s.split(' ');
		        	if(a.length==2)//for hourly date format
		          	{
		          		return s.replace(/\//g, '').replace(/ /g, '').replace(/:/g, ''); //removes comma separator from formatted numbers
		          	}
		        }
		        a = s.split('/');
		        
		        // glue and return a new date
		        return new Date(a[2],a[0]-1,a[1],0, 0, 0, 0).getTime();
		    },
	        
	        // set type, either numeric or text
	        type: 'numeric'
	});
	
	//define a parser
	$.tablesorter.addParser({
		// set a unique id
		id: 'formattedText',
		is: function(s){
			// return false so this parser is not auto detected
			return false;
		},
		format: function(s){
		// format your data for normalization
			return s.replace(/,/g, '').replace(/ /g, '').replace(/-/,'').replace(/\//,''); //removes comma separator from formatted numbers
			
		},
		// set type, either numeric or text
		type: 'text'
	});
	
	$.tablesorter.addWidget({
		id: "zebra",
		format: function(table) {
					$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]) .end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);
		}
	});

//        $(".zebra").tablesorter();
		$("#campaign_data").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			4: { sorter: 'formattedNumbers' }
			}
			
		});
		$("#site_data").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{	
			1: { sorter: 'formattedNumbers' },
			2: { sorter: 'formattedNumbers' },
			3: { sorter: 'formattedNumbers' },
			4: { sorter: 'formattedNumbers' },
			5: { sorter: 'formattedNumbers' }
			}
			
		});
		$("#group_by_site_inventory_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			1: { sorter: 'formattedNumbers' },
			2: { sorter: 'formattedNumbers' },
			3: { sorter: 'formattedNumbers' },
			4: { sorter: 'formattedNumbers' },
			5: { sorter: 'formattedNumbers' }
			}
		});
		$("#group_by_date_inventory_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			1: { sorter: 'formattedNumbers' },
			2: { sorter: 'formattedNumbers' },
			3: { sorter: 'formattedNumbers' },
			4: { sorter: 'formattedNumbers' },
			5: { sorter: 'formattedNumbers' }
			}
		});
		
		$("#group_by_site_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			1: { sorter: 'formattedNumbers' },
			2: { sorter: 'formattedNumbers' },
			4: { sorter: 'formattedNumbers' },
			5: { sorter: 'formattedNumbers' }
			}
		});
		$("#group_by_device_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			1: { sorter: 'formattedNumbers' },
			2: { sorter: 'formattedNumbers' }
			}
		});
		$("#group_by_date_report1").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			0: { sorter: 'formattedDates' },
			1: { sorter: 'formattedNumbers' },
			2: { sorter: 'formattedNumbers' },
			3: { sorter: 'formattedNumbers' },
			4: { sorter: 'formattedNumbers' },
			5: { sorter: 'formattedNumbers' }
			}
		});
		$("#group_by_date_report2").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedDates' },
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' }
			},
			
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		
		//customize the table sorting where we need to
		$("#group_by_date_report,#group_by_campaignname_report,#group_by_bannername_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_date_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' },
				4: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_network_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_country").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_country_site_report,#group_by_banner_site_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedText' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' },
				4: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});


		$("#group_by_campaign_site_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedText' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' },
				4: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});


        $("#group_by_mobile_report,#group_by_pc_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				2: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
        $("#group_by_campaign_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				4: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_country_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_date_report3").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedDates' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_date_report4").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedDates' },
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' },
				4: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_carrier_report2").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_carrier_report","group_by_country").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		$("#group_by_advertiser_report6").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		 $("#raw_ad_requests").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		 $("#index_adnetworks, #index_campaigns").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				2: { sorter: false }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		 $("#group_by_campaign_report3,#group_by_banner_report3").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedText' },
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});

		 $("#group_by_campaign_report6").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedText' },
				1: { sorter: 'formattedText' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' },
				4: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});

		$("#group_by_banner_report6").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedText' },
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});


		$("#group_by_country_campaign_report,#group_by_country_banner_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		
		$("#group_by_date_report6").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedDates' },
				1: { sorter: 'formattedNumbers' },
				2: { sorter: 'formattedNumbers' },
				3: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		
		$("#group_by_analytic_report,#group_by_eventtype_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				1: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		
		$("#group_by_analytic_eventype_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				2: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});
		
		$("#group_by_date_analytic_report").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedDates' },
				1: { sorter: 'formattedNumbers' }
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});

		$("#manage_adnetwork").tablesorter({
			indexing: true,
			textExtraction: 'complex',
			headers:{
				0: { sorter: 'formattedText' },
				1: { sorter: 'formattedText' },
				2: { sorter: false},
				3: { sorter: false},
				4: { sorter: 'formattedNumbers'}
			},
			widgets:['zebra'],
			sortList:[[0,0]]
		});

}
var allowed_custom_data_time_frame = 365;
var ecpmChart=1;
var countCustomParDiv=0;
var countVideoButtonsDiv=0;
var allocCountry = 'All';

function populateStartEndDates(id)
{
	sel_date_option = $('#'+id).val();
	if(sel_date_option=='')
	{
		return false;
	}
	var currentDate = new Date();
	var startdate = new Date();
	var enddate = new Date();

	if(sel_date_option=='today' || sel_date_option=='yesterday' || sel_date_option=='this_week' || sel_date_option=='last_week' ||
		sel_date_option=='last_7_days' || sel_date_option=='this_month' || sel_date_option=='last_30_days' || sel_date_option=='last_month')
	{
		$("#startdate").attr("disabled","true");
		$("#enddate").attr("disabled","true");
		$("#startdate_popup").hide();
		$("#enddate_popup").hide();

		switch(sel_date_option)
		{
			case 'today':
			{
				$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
				$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
				break;
			}
			case 'yesterday':
			{
				startdate.setDate(currentDate.getDate()-1);
				enddate.setDate(currentDate.getDate()-1);

				$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
				$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
				break
			}
			case 'this_week':
			{
				is_monday = currentDate.is().monday();
				if(!is_monday)
				{
					last_monday = currentDate.last().monday()
				}
				else
				{
					last_monday = currentDate;
				}

				startdate = last_monday;

				$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
				$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
				break;
			}
			case 'last_week':
			{
				last_sunday= currentDate.last().sunday()
				enddate = dateFormat(last_sunday,'UTC:mm/dd/yy');

				last_monday = last_sunday.last().monday()
				startdate = dateFormat(last_monday,'UTC:mm/dd/yy');

				$("#startdate").val(startdate);
				$("#enddate").val(enddate);
				break;
			}
			case 'last_7_days':
			{
				startdate.setDate(currentDate.getDate()-7)
				enddate.setDate(currentDate.getDate()-1)

				$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
				$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
				break;
			}
			case 'this_month':
			{
				startdate.setDate(1);
				startdate.setHours(10);//hot fix...so as to get day 1 of the month in GMT

				$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
				$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
				break;
			}
			case 'last_month':
			{
				currentDate.setDate(1);
				last_month_beg = currentDate.last().month();
				startdate = last_month_beg.toString('MM/dd/yy');
				next_month_beg = last_month_beg.next().month();
				last_month_end = next_month_beg.last().day();
				enddate = last_month_end.toString('MM/dd/yy');
				$("#startdate").val(startdate);
				$("#enddate").val(enddate);
				break;
			}
			case 'last_30_days':
			{
				startdate.setDate(currentDate.getDate()-30)
				enddate.setDate(currentDate.getDate()-1)

				$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
				$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
				break;
			}
		}
		//AUTO-Submit the form
		$('[name="frmReport"] #submit').click();
	}
	else
	{
		$("#startdate").attr("disabled","");
		$("#enddate").attr("disabled","");
		$("#startdate_popup").show();
		$("#enddate_popup").show();
	}
}

function updateHomepageReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please select site!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}
	ecpmChart=0;
	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}
function updateHomepageChart(link_id,entity,zoneIds,sel_date_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	sel_affiliate_Id = $("#affiliateId").val();
	if(sel_affiliate_Id == undefined)
	{
		sel_affiliate_Id = -1;
	}
	
	posturl = '/homepage/getDailyReportXMLByZone/' + zoneIds;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option+"&sel_affiliate_Id="+sel_affiliate_Id,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('report_summary',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});

}

function updateAddetailsSiteWiseReport(frm)
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please select site!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please  select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		frm.submit();
	}
	else
	{
		return false;
	}
}

function checkDates(future)
{
	var startField = $('#startdate');
	var endField = $('#enddate');
	var startdate = startField.val();
	var enddate = endField.val();

	var startFieldDisabled = true;
	if(startField.attr("disabled")== undefined || startField.attr("disabled")=="")
	{
		startFieldDisabled = false
	}

	var endFieldDisabled = true;
	if(endField.attr("disabled")== undefined || endField.attr("disabled")=="")
	{
		endFieldDisabled = false
	}

	is_error=false;
	if(!startFieldDisabled && startdate == '')
	{
		is_error=true;
		alert("Please enter valid startdate!");
	}
	else
	{
		var start = Date.parseDate(startdate, '%m/%d/%y');
	}

	if(!endFieldDisabled && enddate == '')
	{
		is_error=true;
		alert("Please enter valid enddate!");
	}
	else
	{
		var end = Date.parseDate(enddate, '%m/%d/%y');
	}

	if (!startFieldDisabled && !endFieldDisabled && !is_error )
	{
		if(start.getTime() > end.getTime())
		{
			is_error=true;
			alert("Startdate should be before Enddate!");
		}
		else
		{
			var one_day=1000*60*60*24;
			var day_diff = Math.ceil((end.getTime()-start.getTime())/(one_day));
			if(day_diff>allowed_custom_data_time_frame)
			{
				is_error=true;
				alert("Max time frame is "+allowed_custom_data_time_frame+" days!");
			}
			else if (future == false)
			{
				/* 
				var currentDate = getCurrentGMTTime();
				if(end.getTime() > currentDate.getTime())
				{
					is_error=true;
					alert("Enddate should not be after CurrentDate!");
				}
				*/
			}
			else if(future)
			{
				var currentDate = getCurrentGMTTime();
				if(start.getTime()<= currentDate.getTime())
				{
					is_error=true;
					alert("Startdate should be after CurrentDate!");
				}
				else if(end.getTime() <= currentDate.getTime())
				{
					is_error=true;
					alert("Enddate should be after CurrentDate!");
				}
			}
		}
	}

	if(is_error)
	{
		return false;
	}

	return true;
}

function showHideReport(id_show, id_hide)
{
	$("#"+id_hide+"_href").removeClass('current');
	$("#"+id_show+"_href").addClass('current');
	$("#"+id_hide).hide();
	$("#"+id_show).show();
	$("#group_by").val(id_show);
}

function showHideReportForMultiple(id_show, id_hide1, id_hide2, id_hide3, id_hide4, id_hide5)
{
	var new_id_show = id_show+"_href";
	var new_id_hide1 = id_hide1+"_href";
	var new_id_hide2 = id_hide2+"_href";
	var new_id_hide3 = id_hide3+"_href";
	var new_id_hide4 = id_hide4+"_href";
	var new_id_hide5 = id_hide5+"_href";

	$("#"+new_id_show).addClass('current');
	$("#"+new_id_hide1).removeClass('current');
	$("#"+new_id_hide2).removeClass('current');
	$("#"+new_id_hide3).removeClass('current');
	$("#"+new_id_hide4).removeClass('current');
	$("#"+new_id_hide5).removeClass('current');

	$("#"+id_hide1).hide();
	$("#"+id_hide2).hide();
	$("#"+id_hide3).hide();
	$("#"+id_hide4).hide();
	$("#"+id_hide5).hide();
	$("#"+id_show).show();
	$("#group_by").val(id_show);
}

function updateSiteWiseDailyChart(link_id,entity,zoneIds,sel_date_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getSiteWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('sitewise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function updateAddetailsCountryWiseReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please  select site!");
		return false;
	}

	sel_country_option = $('#country_options').val();
	if(sel_country_option=='')
	{
		alert("Please select country options!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateTrafficAnalysisReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please  select site!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateCountryWiseDailyChart(link_id,entity,zoneIds,sel_date_option,sel_country_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getCountryWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds+'/'+sel_country_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('countrywise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}
function updateRevenueWiseDailyChart(link_id,entity,zoneIds,sel_date_option,sel_country_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getCountryWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds+'/'+sel_country_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('revenuewise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}
function updateAddetailsNetworkWiseReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please select site!");
		return false;
	}

	sel_adnetwork_option = $('#adnetwork_options').val();
	if(sel_adnetwork_option=='')
	{
		alert("Please select ad network options!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateNetworkWiseDailyChart(link_id,entity,zoneIds,sel_date_option,sel_network_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getNetworkWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds+'/'+sel_network_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('networkwise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function updateAddetailsDeviceWiseReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please select site!");
		return false;
	}

	sel_device_option = $('#device_options').val();
	if(sel_device_option=='')
	{
		alert("Please select device options!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateDeviceWiseDailyChart(link_id,entity,zoneIds,sel_date_option,sel_device_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getDeviceWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds+'/'+sel_device_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('devicewise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function urlencode( str ) {
    // URL-encodes string
    //
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_urlencode/
    // +       version: 809.1713
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}// }}}

function homepagereporttocsv(url_campaign_id)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaign_id='+urlencode(url_campaign_id)+'&groupby='+groupby;
	location.href='/homepageadv/homepagereporttocsv'+urlparams;
}
function sitewisereporttocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby;
	location.href='/addetails/sitewisereporttocsv'+urlparams;
}

function sitesdetailreporttocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/addetails/sitesdetailreporttocsv/'+zoneIds+urlparams;
}

function countrywisereporttocsv(zoneIds,sel_country_option)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby+'&sel_country_option='+urlencode(sel_country_option);
	location.href='/addetails/countrywisereporttocsv'+urlparams;
}

function countriesdetailreporttocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/addetails/countriesdetailreporttocsv/'+zoneIds+urlparams;
}

function devicewisereporttocsv(zoneIds,sel_device_option)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby+'&sel_device_option='+urlencode(sel_device_option);
	location.href='/addetails/devicewisereporttocsv'+urlparams;
}

function devicesdetailreporttocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/addetails/devicesdetailreporttocsv/'+zoneIds+urlparams;
}

function networkwisereporttocsv(zoneIds,url_network_id,campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby+'&network_id='+urlencode(url_network_id)+'&campaignIds='+urlencode(campaignIds);
	location.href='/addetails/networkwisereporttocsv'+urlparams;
}

function networksdetailreporttocsv(zoneIds,url_network_id,hasCampaignViewPerms,hasBannerViewPerms)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&network_id='+urlencode(url_network_id)+'&showCampaigns='+urlencode(hasCampaignViewPerms)+'&showBanners='+urlencode(hasBannerViewPerms);
	location.href='/addetails/networksdetailreporttocsv/'+zoneIds+urlparams;
}

function countrywiseanalysistocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	continent_options = $('#continent_options').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&continent='+urlencode(continent_options);
	location.href='/trafficanalysis/countrywiseanalysistocsv'+urlparams;
}

function countrywiseadvanalysistocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	continent_options = $('#continent_options').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaignIds='+urlencode(campaignIds)+'&continent='+urlencode(continent_options);
	location.href='/trafficanalysisadv/countrywiseanalysistocsv'+urlparams;
}

function countriesdetailanalysistocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	continent_options = $('#continent_options').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&continent='+urlencode(continent_options);
	location.href='/trafficanalysis/countriesdetailanalysistocsv/'+zoneIds+urlparams;
}

function countriesadvdetailanalysistocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	continent_options = $('#continent_options').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&continent='+urlencode(continent_options);
	location.href='/trafficanalysisadv/countriesdetailanalysistocsv/'+campaignIds+urlparams;
}


function sourcewiseanalysistocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby;
	location.href='/trafficanalysis/sourcewiseanalysistocsv'+urlparams;
}

function sourcewiseadvanalysistocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaignIds='+urlencode(campaignIds)+'&groupby='+groupby;
	location.href='/trafficanalysisadv/sourcewiseanalysistocsv'+urlparams;
}

function sourcesdetailanalysistocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/trafficanalysis/sourcesdetailanalysistocsv/'+zoneIds+urlparams;
}

function sourcesdetailadvanalysistocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/trafficanalysisadv/sourcesdetailanalysistocsv/'+campaignIds+urlparams;
}

function updateHomepageChart_Ecpm(link_id,entity,zoneIds,sel_date_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	sel_affiliate_Id = $('#affiliateId').val();
	if(sel_affiliate_Id == undefined)
	{
		sel_affiliate_Id = -1;
	}
	
	posturl = '/homepage/getDailyReportXMLByZoneEcpm/'+ zoneIds;
	ecpmChart=1;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option+"&sel_affiliate_Id="+sel_affiliate_Id,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('report_summary',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function confirmDelete(zoneId)
{
	var msg = "Are you sure you want to delete this site?";
	if( confirm(msg) )
	{
		location.href='/sitemgmt/deletesite/'+zoneId;
	}
	return false;
}

function displayImageFields(storageType)
{
	$("#tr_image").hide();
	$("#tr_txt").hide();
	$("#tr_html").hide();
	$("#tr_javascript").hide();
	$("#tr_html_txt_1").hide();
	$("#tr_html_txt_2").hide();	
	$("#tr_image_1").hide();
	$("#MultiImagesTr").hide();
	$("#tr_image_error").hide();
	$("#banner_name_notes").hide();
	$("#tr_banner_text").hide();
	$("#tr_html_sms_1").hide();
	$("#standard_image_notes").hide();
	$("#custom_image_notes").hide();
	$("#video_notes").hide();
	$("tr[name=pixense_tracking]").show();
	$("#tr_landing_page").hide();

	$("#tr_video_toolbar").hide();
	$("#CustomVideoToolbarHd").hide();
	$("#CustomVideoToolbarTr").hide();
	$("tr[name=tr_video_labels]").hide();

	if(storageType=="sql" || storageType=="web" || storageType=="url")
	{
		$("#tr_image").show();
		$("#tr_image_1").show();
		$("#MultiImagesTr").show();
		$("#tr_image_error").show();
		$("#banner_name_notes").show();
		$("#tr_banner_text").show();
		$("#standard_image_notes").show();
		$("#tr_landing_page").show();
		$("#landing_page_label").html("Destination URL (include http://)");

		$("tr[id^='img_']").remove();

		for (i=0;i<3;i++)
		{
			var code = "";
			code +=  "<tr id='img_"+i+"''>";
			code +=  "   <td> <input name='data[BannerInfo][multiImages]["+i+"]' value='' maxlength='255' id='data[BannerInfo][multiImages]["+i+"]' type='file'>";
			code +=  "   &nbsp;&nbsp;&nbsp;<a href='#' onclick='$(this).parents(\"tr:first\").remove(); return false;' class='deleteCustParam'>Delete</a>";
			code +=  " </td></tr>";
			$("#MultiImagesTable").append(code);
		}
	}
	else if(storageType=="txt")
	{
		$("#tr_txt").show();
	}
	else if(storageType=="html")
	{
		$("#tr_html").show();
	}
	else if(storageType=="javascript")
	{
		$("#tr_javascript").show();
	}
	else if(storageType=="html_txt")
	{
		$("#tr_html_txt_1").show();
		$("#tr_html_txt_2").show();
		$("#tr_landing_page").show();
		$("#landing_page_label").html("Link URL (include http://)");
	}
	else if(storageType=="html_sms")
	{
		$("#tr_html_sms_1").show();
	}
	else if(storageType=="url_custom" )
	{
		$("#tr_image").show();
		$("#tr_image_1").show();
		$("#MultiImagesTr").show();
		$("#tr_image_error").show();
		$("#banner_name_notes").show();
		$("#tr_banner_text").show();
		$("#custom_image_notes").show();
		$("#tr_landing_page").show();
		$("#landing_page_label").html("Destination URL (include http://)");

		$("tr[id^='img_']").remove();
	}
	else if(storageType=="html_video" )
	{
		$("#tr_image").show();
		$("#tr_image_error").show();
		$("#video_notes").show();
		$("#tr_video_toolbar").show();
		$("#CustomVideoToolbarTr").show();
		
		if(countVideoButtonsDiv > -1){
			$("#CustomVideoToolbarHd").show();
		}

		$("tr[name=pixense_tracking]").hide();
		$("tr[name=tr_video_labels]").show();
	}
	else
	{
		$("#tr_sql").show();
	}
}

function setTargetingFields(storageType)
{
	$("#resolutionDivT").show();
	if($("#AclInfoResolution0").attr("checked")==true)
		$("#resolutionDiv").hide();
	if($("#AclInfoResolution1").attr("checked")==true)
		$("#resolutionDiv").show();

	$("#deviceDivT").show();
	$("#deviceOsDivT").show();

	//for device
	if($("#AclInfoDevice0").attr("checked")==true)
	{
		$("#deviceDiv").hide();
		$("#deviceDivNegate").hide();
		uncheckedAllEntityCheckboxes('device',0);
	}
	if($("#AclInfoDevice1").attr("checked")==true)
	{
		$("#deviceDiv").show();
		$("#deviceDivNegate").hide();
		uncheckedAllEntityCheckboxes('device',0);
	}
	if($("#AclInfoDevice2").attr("checked")==true)
	{
		$("#deviceDiv").hide();
		$("#deviceDivNegate").show();
		uncheckedAllEntityCheckboxes('device',0);
	}
	//for deviceos
	if($("#AclInfoDeviceOS0").attr("checked")==true)
	{
		$("#deviceOSDiv").hide();
		$("#deviceOSDivNegate").hide();
		uncheckedAllEntityCheckboxes('deviceOS',0);
	}
	if($("#AclInfoDeviceOS1").attr("checked")==true)
	{
		$("#deviceOSDiv").show();
		$("#deviceOSDivNegate").hide();
		uncheckedAllEntityCheckboxes('deviceOS',0);
	}
	if($("#AclInfoDeviceOS2").attr("checked")==true)
	{
		$("#deviceOSDiv").hide();
		$("#deviceOSDivNegate").show();
		uncheckedAllEntityCheckboxes('deviceOS',0);
	}

	if(storageType == 'url' || storageType == 'html_sms')
	{
		$("#resolutionDivT").hide();
		$("#resolutionDiv").hide();
		$("#resolutionDiv" + " INPUT[type='checkbox']").attr('checked', false);
	}

	if(storageType == 'html_sms')
	{
		$("#deviceDivT").hide();
		$("#deviceDiv").hide();
		$("#deviceDivNegate").hide();
		uncheckedAllEntityCheckboxes('device',0);

		$("#deviceOsDivT").hide();
		$("#deviceOSDiv").hide();
		$("#deviceOSDivNegate").hide();
		uncheckedAllEntityCheckboxes('deviceOS',0);
	}
}

function confirmBannerDelete(bannerId,campaignId)
{
	var msg = "Are you sure you want to delete this banner?";
	if( confirm(msg) )
	{
		location.href='/banner/deletebanner/'+bannerId+'/'+campaignId;
	}
	return false;
}

function confirmCampaignDelete(clientId,campaignId,from)
{
	var msg = "Are you sure you want to delete this campaign?";
	if( confirm(msg) )
	{
		if(from=='adv')
			location.href='/campaign/delete/'+campaignId+'/'+clientId+'?from=adv';
		else
			location.href='/campaign/delete/'+campaignId+'/'+clientId;
	}
	return false;
}

function confirmAdvertiserDelete(advertiserId)
{
	var msg = "Are you sure you want to delete this advertiser?";
	if( confirm(msg) )
	{
		location.href='/advertiser/delete/'+advertiserId;
	}
	return false;
}

function confirmCampaignGroupDelete(groupId)
{
	var msg = "Are you sure you want to delete this Campaign Group?";
	if( confirm(msg) )
	{
		location.href='/campaign/deletegroup/'+groupId;
	}
	return false;
}

function updateDayCheckboxes()
{
    var checked_status = "";
    if ($("#AllDays").attr("checked")==true) checked_status = true;
       $("#monday").attr("checked",checked_status);
       $("#tuesday").attr("checked",checked_status);
       $("#wednesday").attr("checked",checked_status);
       $("#thursday").attr("checked",checked_status);
       $("#friday").attr("checked",checked_status);
       $("#saturday").attr("checked",checked_status);
       $("#sunday").attr("checked",checked_status);
}

function updateCountryCheckBoxes(continent)
{
/*
    var checked_status = "";
    if ($("#"+continent).attr("checked")==true) checked_status = true;
    var tableId=continent+"table";
    upper = document.getElementById(tableId);
    var childCount = upper.getElementsByTagName('tr').length;
    for (i=0;i<childCount+1;i++)
    {
        checkboxElementId=continent+"_"+i;
        $("#"+checkboxElementId).attr("checked",checked_status);
   }
 */
 	//c'mon! jquery is MUCH better than that:
	$("#"+continent+"table INPUT[type='checkbox']").attr('checked', $("#"+continent).attr("checked"));

}

function showHideDayDiv(dayDiv)
{
    if($("#AclInfoDay0").attr("checked")==true)
    {	$("#"+dayDiv).hide();
    	$("#"+dayDiv+"Negate").hide();
    }
    if($("#AclInfoDay1").attr("checked")==true)
    {	$("#"+dayDiv).show();
    	$("#"+dayDiv+"Negate").hide();
    }
    if($("#AclInfoDay2").attr("checked")==true)
    {	$("#"+dayDiv+"Negate").show();
    	$("#"+dayDiv).hide();
    }
}

function showHideCountryDiv(countryDiv)
{
	if($("#AclInfoCarriers1").attr("checked")==false)
	{
		if($("#AclInfoRegion0").attr("checked")==true)
    	{
    		$("#"+countryDiv).hide();
    		$("#"+countryDiv+"Negate").hide();
    	}
	    if($("#AclInfoRegion1").attr("checked")==true)
	    {	$("#"+countryDiv).show();
	    	$("#"+countryDiv+"Negate").hide();
	    }
	    if($("#AclInfoRegion2").attr("checked")==true)
	    {	$("#"+countryDiv+"Negate").show();
	    	$("#"+countryDiv).hide();
	    }
	}
	else
	{
		$("#AclInfoRegion0").attr("checked",'checked');
		$("#"+countryDiv+"Negate").hide();
	    $("#"+countryDiv).hide();
	}
}

function showHideDeviceDiv(deviceDiv)
{
    if($("#AclInfoDevice0").attr("checked")==true)
    {
    	$("#"+deviceDiv).hide();
    	$("#"+deviceDiv+"Negate").hide();
    }
    if($("#AclInfoDevice1").attr("checked")==true)
    {
    	$("#"+deviceDiv).show();
    	$("#"+deviceDiv+"Negate").hide();
    }
    if($("#AclInfoDevice2").attr("checked")==true)
    {
    	$("#"+deviceDiv+"Negate").show();
    	$("#"+deviceDiv).hide();
    }
}


function GetTargetingParameters() {
	var retval = "";
	$.ajax({
		type: "POST",
		url: "/banner/get_targeting_parameters",
		success: function(msg){
			retval=msg;
		},
		async: false 
	});
	return retval;
}

function addNewCustomParDiv(customparDiv)
{
	countCustomParDiv++;
	var code = "";
	if(countCustomParDiv == 0){
		//code += "<tr><td width='130'>Parameter :</td><td width='130'> Comparator :</td><td width='130'>Value : <td><td>&#160;</td></tr>";
		$("#custParamHd").show();
		$("#custParamHd1").html('Display this banner when:');
	}
	code +=  "<tr>";
	
	/************/ 
	var targetingParametersOptions = GetTargetingParameters();
	code +=  "   <td><SELECT style='width:210px;' id='customParamPicker_"+countCustomParDiv+"' name='customParamPicker_"+countCustomParDiv+"'onchange='populateCustomParam("+countCustomParDiv+")' >";
	code +=  targetingParametersOptions;
	code +="</SELECT>&nbsp;";
	code +="<input type='text' size=15 id='customParam_"+countCustomParDiv+"' name='data[Custom]["+countCustomParDiv+"][Parameter]' value=''\>";
	code +="</td>";
	/************/ 

	code +=  "   <td> <SELECT NAME='data[Custom]["+countCustomParDiv+"][Comparator]'><option VALUE='=='> Equal To</option><option VALUE='!='> Not Equal To</option><option VALUE='gt'>Greater Than</option><option VALUE='lt'>Less Than</option><option VALUE='=x'>Matches</option><option VALUE='!x'>Doesn't Match</option></SELECT></td>";
	code +=  "   <td> &nbsp;&nbsp;<input type=text id='customValue_"+countCustomParDiv+"' name='data[Custom]["+countCustomParDiv+"][Value]' size='15'/></td>";
	code +=  "   <td> <a href='#' onclick='$(this).parents(\"tr:first\").remove(); return false;' class='deleteCustParam'>Delete</a></td>";
	code +=  "</tr>";

	$("#"+customparDiv).append(code);
}

function updateDeviceCheckBoxes(device)
{
    /*deviceId=device.replace(" ", "_")
    var checked_status = "";
    if ($("#"+deviceId).attr("checked")==true) checked_status = true;
    var tableId=deviceId+"table";
    var upper = document.getElementById(tableId);
    var childCount = upper.getElementsByTagName('tr').length;
    for (i=0;i<childCount+1;i++)
    {
        checkboxElementId=deviceId+"_"+i;
        $("#"+checkboxElementId).attr("checked",checked_status);
   }*/
   $("#"+device+"table INPUT[type='checkbox']").attr('checked', $("#"+device).attr("checked"));

}

function updateDeviceModelNames(brand,bannerId,action,negate,device,from)
{
	if(action=='') action='add';
	add_param = '';
	if(from != '')
		add_param = '&from='+from;
	isChecked = ($("#"+device).attr("checked") ==true)?1:0;
	deviceId=brand.replace(" ", "_");
    posturl = '/banner/device/'+brand+'/'+bannerId+'/'+ action +'/'+negate+'?isChecked='+isChecked+add_param;
   
    var divName = negate+deviceId + "_div";
	var deviceHasChildChecked = negate+deviceId+"_deviceHasChildren"
	if ($("#"+deviceHasChildChecked).length==0)
	{
	    $("#"+divName).html('fetching ' + brand + ' devices...');
	    $.ajax({
	        type: "POST",
	        url: posturl,
	        success: function(msg){
	                $("#"+divName).html(msg);
	                if($("#"+deviceHasChildChecked).attr("checked")==true)
	                 $("#"+negate+deviceId).attr('checked','checked');
	               },
			error:function(){
	                $("#"+divName).html('There was an error fetching devices.');
				}
	        });
	}
}

function showHideResolutionDiv(resolutionDiv)
{

    if($("#AclInfoResolution0").attr("checked")==true)  $("#"+resolutionDiv).hide();
    if($("#AclInfoResolution1").attr("checked")==true)  $("#"+resolutionDiv).show();
}

function showHideCarrierDiv(carrierDiv,toggleCountrySelection)
{
	if($("#AclInfoCarriers0").attr("checked")==true)
   	{
   		$("#"+carrierDiv).hide();
   		$("#"+carrierDiv+"Negate").hide();
   	}

    if($("#AclInfoCarriers1").attr("checked")==true)
    {
    	$("#"+carrierDiv).show();
    	$("#"+carrierDiv+"Negate").hide();

		if(toggleCountrySelection == true)
		{
			$("#AclInfoRegion0").attr('checked','checked');
			$("#countryDiv").hide();
			$("#countryDivNegate").hide();
		}
    }
    if($("#AclInfoCarriers2").attr("checked")==true)
    {
    	$("#"+carrierDiv+"Negate").show();
    	$("#"+carrierDiv).hide();
    }
}

function showHideOtherChannelsDiv(otherChannelsDiv)
{
	if($("#AclInfoOtherchannels0").attr("checked")==true)
   	{
   		$("#"+otherChannelsDiv).hide();
   		$("#"+otherChannelsDiv+"Negate").hide();
   	}
    if($("#AclInfoOtherchannels1").attr("checked")==true)
    {
    	$("#"+otherChannelsDiv).show();
    	$("#"+otherChannelsDiv+"Negate").hide();
    }
    if($("#AclInfoOtherchannels2").attr("checked")==true)
    {
    	$("#"+otherChannelsDiv+"Negate").show();
    	$("#"+otherChannelsDiv).hide();
    }
}

function showHideInstallCode(languages,selectedLanguage)
{
    for (i=0;i<languages.length;i++)
    {    var divName = languages[i]+"Snippet";
         if (languages[i] != selectedLanguage)
        {
            $("#"+divName).hide();
        }
        else
        {
			$('.navLinks').children().removeClass('current');
				$('#nl_'+selectedLanguage).addClass('current');
				$("#"+divName).show();
        }
    }
}
function reportdatatocsv(reportdate,startdate,enddate)
{
	user_id = $('#user_id').val();
	urlparams = '?reportdate='+urlencode(reportdate)+'&user_id='+urlencode(user_id)+'&startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/admin/reportdatatocsv'+urlparams;
}

function carrierwiseanalysistocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds);
	location.href='/trafficanalysis/carrierwiseanalysistocsv'+urlparams;
}

function carrierwiseadvanalysistocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaignIds='+urlencode(campaignIds);
	location.href='/trafficanalysisadv/carrierwiseanalysistocsv'+urlparams;
}

function carrierdetailanalysistocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/trafficanalysis/carrierdetailanalysistocsv/'+zoneIds+urlparams;
}

function carrierdetailadvanalysistocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/trafficanalysisadv/carrierdetailanalysistocsv/'+campaignIds+urlparams;
}


function updateAddetailsCarrierWiseReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please  select site!");
		return false;
	}

	sel_carrier_option = $('#carrier_options').val();
	if(sel_carrier_option=='')
	{
		alert("Please select carrier options!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateCarrierWiseDailyChart(link_id,entity,zoneIds,sel_date_option,sel_carrier_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getCarrierWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds+'/'+sel_carrier_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('carrierwise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function carrierwisereporttocsv(zoneIds,sel_carrier_option)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby+'&sel_carrier_option='+urlencode(sel_carrier_option);
	location.href='/addetails/carrierwisereporttocsv'+urlparams;
}

function carriersdetailreporttocsv(zoneIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/addetails/carriersdetailreporttocsv/'+zoneIds+urlparams;
}

function updateCampaignWiseDailyChart(link_id,entity,zoneIds,sel_date_option,sel_campaign_option,sel_network_id, filter_by)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/addetails/getCampaignWiseDailyReportXMLByEntity/'+ entity + '/' + zoneIds;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option+'&sel_campaign_option='+sel_campaign_option+'&sel_network_id='+sel_network_id+'&filter_by='+filter_by,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('campaignwise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function updateCampaignWiseDailyChartAdv(link_id,entity,sel_date_option,sel_campaign_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/campaigndetailsadv/getCampaignWiseDailyReportXMLByEntity/'+ entity + '/' +sel_campaign_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('campaignwise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function updateAddetailsCampaignWiseReport()
{
	sel_campaign_option = $('#campaign_options').val();
	if(sel_campaign_option=='')
	{
		alert("Please select campaign options!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function campaignwisereporttocsv(zoneIds,url_campaign_id,network_id,filter_by)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&groupby='+groupby+'&campaign_id='+urlencode(url_campaign_id)+'&network_id='+urlencode(network_id)+'&filter_by='+urlencode(filter_by);
	location.href='/addetails/campaignwisereporttocsv'+urlparams;
}
function activecampaingreporttocsv(zoneIds)
{
	urlparams = '?zoneIds='+urlencode(zoneIds);
	location.href='/campaign/activecampaingreporttocsv'+urlparams;
}

function campaignwiseadvreporttocsv(url_campaign_id)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaign_id='+urlencode(url_campaign_id)+'&groupby='+urlencode(groupby);
	location.href='/campaigndetailsadv/campaignwisereporttocsv'+urlparams;
}

function campaignsdetailreporttocsv(zoneIds,url_campaign_id,url_network_id,filter_by)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&zoneIds='+urlencode(zoneIds)+'&campaign_id='+urlencode(url_campaign_id)+'&network_id='+urlencode(url_network_id)+'&groupby='+urlencode(groupby)+'&filter_by='+urlencode(filter_by);
	location.href='/addetails/campaignsdetailreporttocsv/'+urlparams;
}

function campaignsdetailadvreporttocsv(url_campaign_id)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaign_id='+urlencode(url_campaign_id)+'&groupby='+urlencode(groupby);
	location.href='/campaigndetailsadv/campaignsdetailreporttocsv/'+urlparams;
}

function updateBannerStatus(bannerId,statusvalue,i,j,k,from)
{
	urlparams = '?i='+urlencode(i)+'&j='+urlencode(j)+'&k='+urlencode(k)+'&from='+urlencode(from);
	posturl = '/banner/activatebanner/'+bannerId+'/'+statusvalue+urlparams;
	var divName = i+'_'+j+'_'+k + "_bannerdiv";
	var divStatusName = i+'_'+j+'_'+ k + "_statusdiv";
	$.ajax({
		type: "POST",
		url: posturl,
		success: function(msg){
			$("#"+divName).html(msg);
			if (document.getElementById('num_active_banner')!=null)
			{
				var num_active_banner = getText(document.getElementById('num_active_banner'));
			}
			if(statusvalue==1)
			{
				$("#"+divStatusName).html('Paused');
				var divBannerStatusValueName = i+'_'+j+'_'+ k + "_statusdiv_val";
				$("#"+divBannerStatusValueName).val('Paused');
				num_active_banner--;
			}
			else
			{
				$("#"+divStatusName).html('');
				var divBannerStatusValueName = i+'_'+j+'_'+ k + "_statusdiv_val";
				$("#"+divBannerStatusValueName).val('');
				num_active_banner++;
			}
			if (document.getElementById('num_active_banner')!=null)
			{
				$("#num_active_banner").html(num_active_banner);
			}
		},
		error:function(){
			$("#"+divName).html('There was an error updating in status.');
		}
	});
}

function updateCampaignStatus(campaignId,statusvalue,i,j,num_banner,from)
{
	urlparams = '?i='+urlencode(i)+'&j='+urlencode(j)+'&num_banner='+urlencode(num_banner)+'&from='+urlencode(from);
	posturl = '/campaign/activatecampaign/'+campaignId+'/'+statusvalue+'/'+urlparams;
	var divName = i+'_'+j+"_campaigndiv";
	var divStatusName = i+'_'+j+ "_campaignstatusdiv";
	var num_active_campaign = getText(document.getElementById('num_active_campaign'));

	$.ajax({
		type: "POST",
		url: posturl,
		success: function(msg){
			if(statusvalue=="1")
			{
				if (from == 'adv')
				{
					j='';
				}
				$("#"+divStatusName).html('Paused');
				num_active_campaign--;
				for(var k=1; k<=num_banner; k++)
				{
					var divBannerName = i+'_'+j+'_'+k + "_div";
					$("#"+divBannerName).hide();
					var divBannerStatusName = i+'_'+j+'_'+ k + "_statusdiv";
					var divBannerStatusValueName = i+'_'+j+'_'+ k + "_statusdiv_val";
					var statusmsg = $("#"+divBannerStatusValueName).val();
					$("#"+divBannerStatusName).html("");
				}
			}
			else
			{
				if (from == 'adv')
				{
					j='';
				}
				$("#"+divStatusName).html('Running');
				num_active_campaign++;
				for(var k=1; k<=num_banner; k++)
				{
					var divBannerName = i+'_'+j+'_'+k + "_div";
					$("#"+divBannerName).show();
					var divBannerStatusName = i+'_'+j+'_'+ k + "_statusdiv";
					$("#"+divBannerStatusName).show();
					var divBannerStatusValueName = i+'_'+j+'_'+ k + "_statusdiv_val";
					var statusmsg = $("#"+divBannerStatusValueName).val();
					$("#"+divBannerStatusName).html(statusmsg);
				}
			}
			$("#num_active_campaign").html(num_active_campaign);
			$("#"+divName).html(msg);
		},
		error:function(){
			$("#"+divName).html('There was an error updating in status.');
		}
	});
}

function getText(n)
{
  if('textContent' in n) {
    return n.textContent;
  } else if('innerText' in n) {
    return n.innerText;
  } else {
    // Call a custom collecting function, throw an error, something like that.
  }
}

function checkStartAndEndDates(dropdown)
{
	startId = "startTimeForAllDaysHours";
	endId = "endTimeForAllDaysHours";

	selected_start_hour = $("#startTimeForAllDaysHours").val();
	selected_end_hour = $("#endTimeForAllDaysHours").val();

	if (dropdown=="startTime")
	{
		min=eval($("#"+startId).val());
		min = min+1;
		for(i=0;i<=23;i++)
		{
			$("#endTimeForAllDaysHours option[value='"+i+"']").remove();
		}
		for (i=min;i<24;i++)
		{
			newOpt = "<option value=" +i+">"+i+"</option>";
			$("#endTimeForAllDaysHours").append(newOpt);
		}

		if(selected_end_hour>=min)
		{
			$("#endTimeForAllDaysHours").val(selected_end_hour);
		}
		else
		{
			$("#endTimeForAllDaysHours").val(23);
		}
	}
	else
	{
		max=$("#"+endId).val();
		for(i=0;i<=23;i++)
		{
			$("#startTimeForAllDaysHours option[value='"+i+"']").remove();
		}
		for (i=0;i<max;i++)
		{
			newOpt = "<option value=" +i+">"+i+"</option>";
			$("#startTimeForAllDaysHours").append(newOpt);
		}

		if(selected_start_hour<max)
		{
			$("#startTimeForAllDaysHours").val(selected_start_hour);
		}
		else
		{
			$("#startTimeForAllDaysHours").val(0);
		}
	}
}

function enableCapping()
{
	$("#capping").attr("disabled","");
	$("#block").attr("disabled","");
	$("#capping").val("3");
	$("#block").val("24");
}

function disableCapping()
{
	$("#capping").attr("disabled","true");
	$("#block").attr("disabled","true");
	$("#capping").val("");
	$("#block").val("");
}

function updateHourCheckboxes()
{
    var checked_status = "";
    if ($("#AllHours").attr("checked")==true) checked_status = true;
	for(i=0;i<24;i++)
	{
		$("#"+i+"_hour").attr("checked",checked_status);
	}
}

function showHideHourDiv(hourDiv)
{
    if($("#AclInfoTime0").attr("checked")==true)
    {
    	$("#"+hourDiv).hide();
    	$("#"+hourDiv+"Negate").hide();
    }
    if($("#AclInfoTime1").attr("checked")==true)
    {
    	$("#"+hourDiv).show();
    	$("#"+hourDiv+"Negate").hide();
    }
    if($("#AclInfoTime2").attr("checked")==true)
    {
    	$("#"+hourDiv+"Negate").show();
    	$("#"+hourDiv).hide();
    }
}

function submitform(frm)
{
	$('[name="'+frm+'"] #submit').click();
}

function updateSelectedCountryAlloc(country,divid)
{
	allocCountry = country;
	$("#"+divid).attr("class","current chartit");
	return false;
}

function validatepublisherfrm()
{
	user_id = $("#user_id").val();
	if(user_id == 0)
	{
		alert("Please do select the customer!");
		return false;
	}
	else return true;
}
function publisherrevenueanalysistocsv(publisherId)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&publisherId='+urlencode(publisherId)+'&groupby='+urlencode(groupby);;
	location.href='/profile/publisherrevenueanalysistocsv'+urlparams;
}

function validatepublisherfrm()
{
	user_id = $("#publisherId").val();
	if(user_id == 0)
	{
		alert("Please do select the publisher!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}

	return true;
}

function updateHomepageadvChart(link_id,entity,campaignIds,sel_date_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/homepageadv/getDailyReportXMLByCampaignName/' + campaignIds;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('report_summary',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function updateHomepageadvChart_Ecpm(link_id,entity,campaignIds,sel_date_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/homepageadv/getDailyReportXMLByCampaignNameEcpm/' + campaignIds;
	ecpmChart=1;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('report_summary',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function updateHomepageadvReport()
{
	sel_campaignId = $('#campaignId').val();
	if(sel_campaignId=='')
	{
		alert("Please select campaign!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}
	ecpmChart=0;
	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function homepageadvreporttocsv(url_campaign_id)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaign_id='+urlencode(url_campaign_id)+'&groupby='+urlencode(groupby);;
	location.href='/homepageadv/homepageanalysistocsv'+urlparams;
}
//Banner Hovering :plugin files: css/jquery.cluetip.css and js/jquery.cluetip.js
$(document).ready(function() {
$('td').cluetip({attribute: 'rel', hoverClass: 'highlight'});
$('td').cluetip({width: 340});
});

function showHideDeviceOSDiv(deviceOSDiv)
{
	if($("#AclInfoDeviceOS0").attr("checked")==true)
	{
		$("#"+deviceOSDiv).hide();
		$("#"+deviceOSDiv+"Negate").hide();
	}
	if($("#AclInfoDeviceOS1").attr("checked")==true)
	{
		$("#"+deviceOSDiv).show();
		$("#"+deviceOSDiv+"Negate").hide();
	}
	if($("#AclInfoDeviceOS2").attr("checked")==true)
	{
		$("#"+deviceOSDiv+"Negate").show();
		$("#"+deviceOSDiv).hide();
	}
}

function updateCampaigndetailsCountryWiseReport()
{
	sel_campaignId = $('#campaignId').val();
	if(sel_campaignId=='')
	{
		alert("Please  select campaign!");
		return false;
	}

	sel_country_option = $('#country_options').val();
	if(sel_country_option=='')
	{
		alert("Please select country options!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateCountryWiseDailyChartAdv(link_id,entity,sel_campaign_option,sel_date_option,sel_country_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/campaigndetailsadv/getCountryWiseDailyReportXMLByEntity/'+ entity + '/' +'/'+sel_campaign_option+ '/'+ sel_country_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('countrywise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function countrywiseadvreporttocsv(campaignIds,sel_country_option)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaignIds='+urlencode(campaignIds)+'&groupby='+groupby+'&sel_country_option='+urlencode(sel_country_option);
	location.href='/campaigndetailsadv/countrywisereporttocsv'+urlparams;
}

function countriesdetailadvreporttocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/campaigndetailsadv/countriesdetailreporttocsv/'+campaignIds+urlparams;
}

function updateDeviceWiseDailyChartAdv(link_id,entity,campaignIds,sel_date_option,sel_device_option)
{
	link_id = link_id;
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/campaigndetailsadv/getDeviceWiseDailyReportXMLByEntity/'+ entity + '/' + campaignIds+'/'+sel_device_option;
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&sel_date_option="+sel_date_option,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('devicewise_daily_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function devicewiseadvreporttocsv(campaignIds,sel_device_option)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();

	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&campaignIds='+urlencode(campaignIds)+'&groupby='+groupby+'&sel_device_option='+urlencode(sel_device_option);
	location.href='/campaigndetailsadv/devicewisereporttocsv'+urlparams;
}

function devicesdetailadvreporttocsv(campaignIds)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate);
	location.href='/campaigndetailsadv/devicesdetailreporttocsv/'+campaignIds+urlparams;
}

function addNewBannerImageDiv(bannerImageDiv)
{
	countMultiImagesDiv++;
	var code = "";
	code +=  "<tr id='img_"+countMultiImagesDiv+"''>";
	code +=  "   <td> <input name='data[BannerInfo][multiImages]["+countMultiImagesDiv+"]' value='' maxlength='255' id='data[BannerInfo][multiImages]["+countMultiImagesDiv+"]' type='file'>";
	code +=  "   &nbsp;&nbsp;&nbsp;<a href='#' onclick='$(this).parents(\"tr:first\").remove(); return false;' class='deleteCustParam'>Delete</a>";
	code +=  " </td></tr>";

	$("#"+bannerImageDiv).append(code);
}

function deleteBannerImageDiv(obj, count)
{
	$(obj).parents("tr:first").remove();
	idtohide = "multi_image_error_"+count;
	$("#"+idtohide).hide();
}

function showHideAnalysisCustomerTR()
{
	if($("#CustomerAll0").attr("checked")==true)
	{
		$("#analysisCustomerTR").hide();
	}
	else if ($("#CustomerAll1").attr("checked")==true)
	{
		$("#analysisCustomerTR").show();
	}
}

function showHideanalysisCustomerNetworkTR()
{
	if($("#NetworkAll0").attr("checked")==true)
	{
		$("#analysisNetworkTR").hide();
	}
	else if ($("#NetworkAll1").attr("checked")==true)
	{
		$("#analysisNetworkTR").show();
	}
}

function updateDeviceModelNamesWithChecks(device)
{
	if(($("#twd_"+device).attr("class")) == "twd up")
	{
		$("#twd_"+device).click();
	}
	else
	{
		updateDeviceCheckBoxes(device);
	}
}

function displayUserFields(obj)
{
	if($("#showhide_acc").hasClass('show'))
	{
		$("#showhide_acc").removeClass('show');
		$("#display_user").show();
	}
	else
	{
		$("#showhide_acc").addClass('show');
		$("#display_user").hide();
	}
}
function showHideDiv(id_show, id_hide)
{
	$("#"+id_hide).hide();
	$("#"+id_show).show();
}

var CARRIER_TARGETING_DELTA_BID_AMOUNT = 0.0000;
var DEVICE_TARGETING_DELTA_BID_AMOUNT = 0.0000;
var DEVICEOS_TARGETING_DELTA_BID_AMOUNT = 0.0000;
var BID_NOT_AVAILABLE_SYMBOL = '--';

function loadGlobalContantsForBidUpload(carrierTargetingDeltaBidAmnt,deviceTargetingDeltaBidAmnt, deviceOSTargetingDeltaBidAmnt, bidNotAvailableSymbol )
{
	CARRIER_TARGETING_DELTA_BID_AMOUNT = carrierTargetingDeltaBidAmnt;
	DEVICE_TARGETING_DELTA_BID_AMOUNT = deviceTargetingDeltaBidAmnt;
	DEVICEOS_TARGETING_DELTA_BID_AMOUNT = deviceOSTargetingDeltaBidAmnt;

	BID_NOT_AVAILABLE_SYMBOL = bidNotAvailableSymbol;
}

function updateCampaignBidInfo(entityName,country,agencyId,ctype,id, isedit)
{
	if(id==0 || id==1)
	{
		isChecked = id;
	}
	else
	{
		isChecked = $('#'+id).attr("checked");
		if(isChecked) isChecked=1
		else isChecked=0
	}

	posturl = '/campaign/getCampaignBidInfosByCountry/' + entityName + '/' + country + '/' + agencyId + '/' + ctype + '/' + isChecked;
	$.ajax({
		type: "POST",
		url: posturl,
		dataType: "json",
		success: function(responseData){
				min_bid_amount = responseData.min_bid_amount;
				max_bid_amount = responseData.max_bid_amount;

				min_val = $('#min_bid_amount').val();
				max_val = $('#max_bid_amount').val();
				bid_val = $('#bid_amount').val();

				if(bid_val == BID_NOT_AVAILABLE_SYMBOL)
					bid_val = 0;

				//check for hidden variables and add amount according to selection of checkboxes
				var add_amount = 0;
				var is_carrier = $("#is_carrier_added").val();
				var is_device = $("#is_device_added").val();
				var is_deviceOS = $("#is_deviceOS_added").val();

				if(is_carrier == 1)
					add_amount = parseFloat(add_amount) + parseFloat(CARRIER_TARGETING_DELTA_BID_AMOUNT);
				if(is_device == 1)
					add_amount = parseFloat(add_amount) + parseFloat(DEVICE_TARGETING_DELTA_BID_AMOUNT);
				if(is_deviceOS == 1)
					add_amount = parseFloat(add_amount) + parseFloat(DEVICEOS_TARGETING_DELTA_BID_AMOUNT);

				if(min_bid_amount == BID_NOT_AVAILABLE_SYMBOL)
				{
					min_bid_amount = parseFloat(add_amount);
				}
				else
				{
					min_bid_amount = parseFloat(min_bid_amount) + parseFloat(add_amount);
				}

				if(max_bid_amount == BID_NOT_AVAILABLE_SYMBOL)
				{
					max_bid_amount = parseFloat(add_amount);
				}
				else
				{
					max_bid_amount = parseFloat(max_bid_amount) + parseFloat(add_amount);
				}


				if(isedit == 0)//for add flow
				{
					bid_val = parseFloat(bid_val) + parseFloat(add_amount);

					if(parseFloat(bid_val) <= parseFloat(min_bid_amount))
						bid_val = min_bid_amount;
					else if (parseFloat(bid_val) >= parseFloat(max_bid_amount))
						bid_val = max_bid_amount;
				}
				setBidValues(min_bid_amount,max_bid_amount,bid_val);
			}
		});
}

function uncheckedAllEntityCheckboxes(entity,isedit)
{
	//unchecked all carriers
	$("#"+entity+"Div1" + " INPUT[type='checkbox']").attr('checked', false);
	$("#"+entity+"Div2" + " INPUT[type='checkbox']").attr('checked', false);

	var is_entity_id = "is_"+entity+"_added";
	var is_entity = $("#"+is_entity_id).val();
	if(is_entity == 1)
	{
		$("#"+is_entity_id).val(0);
		calculateBidValues(entity,'subtract',isedit);
	}
}

function updateCampaignBidInfoForEntity(entity,num_of_ids,id_start,isedit)
{
	var action = '';
	var is_entity_id = "is_"+entity+"_added";
	var is_entity = $("#"+is_entity_id).val();

	var num_of_checked = 0;
	for(var i=1; i<=num_of_ids; i++)
	{
		if($("#"+id_start+i).attr("checked")==true)
		{
			num_of_checked++;
		}
		if(num_of_checked == 1)
			break;
	}
	if(num_of_checked == 1 && is_entity == 0)
	{
		//add bid amount
		action = 'add';
		$('#'+is_entity_id).val(1);
	}
	else if(num_of_checked==0 && is_entity == 1)
	{
		//subtract bid amount
		action = 'subtract';
		$('#'+is_entity_id).val(0);
	}
	calculateBidValues(entity,action,isedit);
}

function updateCampaignBidInfoForDevice(deviceIds,id_start,isedit,id)
{
	var action = '';
	var is_device = $("#is_device_added").val();
	var num_of_checked = 0;

	if ($("#"+id).attr("checked")==true)
		num_of_checked++;

	if(num_of_checked == 0)
	{
		for (var i = 0; i < deviceIds.length; i++)
		{
			var device = id_start+deviceIds[i];
			var deviceId=device.replace(" ", "_");

			if ($("#"+deviceId).attr("checked")==true)
				num_of_checked++;

			var tableId=deviceId+"table";
			var childCount = $("#"+tableId).find('tr').length;
			for (j=0;j<childCount+1;j++)
			{
				checkboxElementId=deviceId+"_"+j;
				if($("#"+checkboxElementId).attr("checked")==true)
					num_of_checked++;
			}
			if(num_of_checked == 1)
				break;
		}
	}

	if(num_of_checked == 1 && is_device == 0)
	{
		//add bid amount
		action = 'add';
		$('#is_device_added').val(1);
	}
	else if(num_of_checked==0 && is_device == 1)
	{
		//subtract bid amount
		action = 'subtract';
		$('#is_device_added').val(0);
	}
	calculateBidValues('device',action,isedit);
}

function calculateBidValues(entity,action,isedit)
{
	amount = 0;

	if(entity == 'carrier')
		amount = CARRIER_TARGETING_DELTA_BID_AMOUNT;
	if(entity == 'device')
		amount = DEVICE_TARGETING_DELTA_BID_AMOUNT;
	if(entity == 'deviceOS')
		amount = DEVICEOS_TARGETING_DELTA_BID_AMOUNT;


	min_val = $('#min_bid_amount').val();
	max_val = $('#max_bid_amount').val();
	bid_val = $('#bid_amount').val();
	if(min_val == BID_NOT_AVAILABLE_SYMBOL)
		min_val = 0;
	if(max_val == BID_NOT_AVAILABLE_SYMBOL)
		max_val = 0;
	if(bid_val == BID_NOT_AVAILABLE_SYMBOL)
		bid_val = 0;

	if(action == 'add')
	{
		min_val = parseFloat(min_val) + parseFloat(amount);
		max_val = parseFloat(max_val) + parseFloat(amount);
	}
	else if(action == 'subtract')
	{
		min_val = parseFloat(min_val) - parseFloat(amount);
		max_val = parseFloat(max_val) - parseFloat(amount);
	}
	else
	{
		//alert('Dont do anything');
	}

	if(isedit == 0)//for add flow
	{
		if(parseFloat(bid_val) <= parseFloat(min_val))
			bid_val = parseFloat(min_val);
		else if (parseFloat(bid_val) >= parseFloat(max_val))
			bid_val = parseFloat(max_val);
	}
	setBidValues(min_val,max_val,bid_val)
}

function setBidValues(min_val,max_val,bid_val)
{
	//set values
	if(min_val <= 0)
	{
		$('#min_bid_amount').val(BID_NOT_AVAILABLE_SYMBOL);
		$('#min_bid_amount_span').html(BID_NOT_AVAILABLE_SYMBOL);
	}
	else
	{
		min_val = custRound(min_val,4);
		$('#min_bid_amount').val(min_val);
		$('#min_bid_amount_span').html(min_val);
	}
	if(max_val == 0)
	{
		$('#max_bid_amount').val(BID_NOT_AVAILABLE_SYMBOL);
		$('#max_bid_amount_span').html(BID_NOT_AVAILABLE_SYMBOL);
	}
	else
	{
		max_val = custRound(max_val,4);
		$('#max_bid_amount').val(max_val);
		$('#max_bid_amount_span').html(max_val);
	}

	if(bid_val != BID_NOT_AVAILABLE_SYMBOL)
			bid_val = custRound(bid_val,4);

	$('#bid_amount').val(bid_val);
}

function custRound(x,places)
{
	return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)
}

function updateCustomCountryReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please do select site!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please do select the date options!");
		return false;
	}

	if(checkDates(false))
	{
		$('#startdate_hidden').val($('#startdate').val()) ;
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
}

function updateInventoryChart (what, site_ids, link_id)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	posturl = '/inventory/getHistoricalPerformanceXMLBySite';
	$.ajax({
		type: "POST",
		url: posturl,
		data: "startdate="+startdate+"&enddate="+enddate+"&site_ids="+site_ids+'&what='+what,
		dataType: "json",
		success: function(msg){
				xml = msg.xml;
				updateChartXML('inventory_chart',xml);
				$('.navLinks').children().removeClass('current');
				$('#'+link_id).addClass('current');
			}
		});
}

function inventory_historical_fill(site_ids)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	groupby = $("#group_by").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&site_ids='+urlencode(site_ids)+'&groupby='+groupby;
	location.href='/inventory/historical_fill_to_csv'+urlparams;

}

function inventory_forecasting(site_ids)
{
	startdate = $('#startdate').val();
	enddate = $('#enddate').val();
	ctr = $("#ctr").val();
	urlparams = '?startdate='+urlencode(startdate)+'&enddate='+urlencode(enddate)+'&site_ids='+urlencode(site_ids)+'&ctr='+ctr;
	location.href='/inventory/inventory_forecast_to_csv'+urlparams;
}

//Jquery plugin  jqmodal

/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: true,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);



/******************End jquery modal**********************/
/********************************************************/


function populateStartEndDatesForForecasting(id)
{
	sel_date_option = $('#'+id).val();
	if(sel_date_option=='')
	{
		return false;
	}
	var currentDate = new Date();
	var startdate = new Date();
	var enddate = new Date();
	
//Next 7 days, Next month, Next 30 days, Next 3 months
	if(sel_date_option == 'specific')
	{
		$("#startdate").attr("disabled","");
		$("#enddate").attr("disabled","");
		$("#startdate_popup").show();
		$("#enddate_popup").show();
	}
	else
	{
		$("#startdate").attr("disabled","true");
		$("#enddate").attr("disabled","true");
		$("#startdate_popup").hide();
		$("#enddate_popup").hide();
		
		if(sel_date_option=='next_7_days')
		{
			startdate.setDate(currentDate.getDate()+1)
			enddate.setDate(currentDate.getDate()+7)

			$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
			$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
		}
		else if(sel_date_option=='next_month')
		{
			currentDate.setDate(1);
			next_month_beg = currentDate.next().month();
			startdate = next_month_beg.toString('MM/dd/yy');
			next_next_month_beg = next_month_beg.next().month();
			next_month_end = next_next_month_beg.last().day();
			enddate = next_month_end.toString('MM/dd/yy');
			$("#startdate").val(startdate);
			$("#enddate").val(enddate);
		}
		else if(sel_date_option=='next_30_days')
		{
			startdate.setDate(currentDate.getDate()+1)
			enddate.setDate(currentDate.getDate()+30)
			$("#startdate").val(dateFormat(startdate,'UTC:mm/dd/yy'));
			$("#enddate").val(dateFormat(enddate,'UTC:mm/dd/yy'));
		}
		else if(sel_date_option=='next_3_months')
		{
			currentDate.setDate(1);
			first = currentDate.next().month();
			startdate = first.toString('MM/dd/yy');
			$("#startdate").val(startdate);
			temp = currentDate.next().month().next().month().next().month();;
			third  = temp;
			third_month_end = third.last().day();
			enddate = third_month_end.toString('MM/dd/yy');
			$("#enddate").val(enddate);
		}
		else
		{
			$("#startdate").attr("disabled","");
			$("#enddate").attr("disabled","");
			$("#startdate_popup").show();
			$("#enddate_popup").show();
		}
		//AUTO-Submit the form
		$('[name="frmReport"] #submit').click();
	}
}

function updateForecastingReport()
{
	sel_zoneId = $('#zoneId').val();
	if(sel_zoneId=='')
	{
		alert("Please select site!");
		return false;
	}

	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}
	sel_date_option = $('#date_options').val();
	if(sel_date_option=='')
	{
		alert("Please select the date options!");
		return false;
	}
	
	ctr = $('#ctr').val();
	if(ctr<=0)
	{
		alert("Please enter the valid ctr!");
		return false;
	}
	
	if(checkDates(true))
	{
		$('#startdate_hidden').val($('#startdate').val());
		$('#enddate_hidden').val($('#enddate').val());
		return true;
	}
	else
	{
		return false;
	}
	return true;
}

function getCurrentGMTTime()
{
	var tempDate = new Date().toGMTString();
	var tempDateArr = tempDate.split(" ");
	var months = {};
	months["Jan"] = "00";
	months["Feb"] = "01";
	months["Mar"] = "02";
	months["Apr"] = "03";
	months["May"] = "04";
	months["Jun"] = "05";
	months["Jul"] = "06";
	months["Aug"] = "07";
	months["Sep"] = "08";
	months["Oct"] = "09";
	months["Nov"] = "10";
	months["Dec"] = "11"; 
	
	var currentDate = new Date(tempDateArr[3],months[tempDateArr[2]],tempDateArr[1],0,0,0,0);
	return currentDate;
}

function enableLandingPageSelection()
{
	$("#landingpage").attr("disabled","");
	
	landingpageurlprefix = ($("#landingpageurlprefix").val());
	storagetype = ($("#storagetype").val());
	pageId = ($("#landingpage").val());
	url = landingpageurlprefix + pageId;
	if(storagetype == "url" || storagetype == "url_custom" )
	{
		$("#url").val(url);
		$("#url").attr("readonly","true");
	}
	else if(storagetype == "html_txt")
	{
		$("#url_link").val(url);
		$("#url_link").attr("readonly","true");
	}
}

function disableLandingPageSelection()
{
	$("#landingpage").attr("disabled","true");
	storagetype = ($("#storagetype").val());
	if(storagetype == "url" || storagetype == "url_custom")
	{
		$("#url").val("");
		$("#url").attr("readonly","");
	}
	else if(storagetype == "html_txt")
	{
		$("#url_link").val("");
		$("#url_link").attr("readonly","");
	}
}

function selectLandingPage(pageId)
{
	storagetype = ($("#storagetype").val());
	landingpageurlprefix = ($("#landingpageurlprefix").val());
	url = landingpageurlprefix + pageId;
	if(storagetype == "url" || storagetype == "url_custom")
	{
		$("#url").val(url);
		$("#url").attr("readonly","true");
	}
	else if(storagetype == "html_txt")
	{
		$("#url_link").val(url);
		$("#url_link").attr("readonly","true");
	}
}

function selectdeselectallzones(obj)
{
	if(obj.checked)
	{
		$("input[id^='"+obj.value+"_']").attr("checked",true);
	}
	else
	{
		$("input[id^='"+obj.value+"_']").attr("checked","");
	}
}

function populateCustomParam(id)
{
	value = $('#customParamPicker_'+id).val();
	if(value=='Custom')
	{
		$("#customParam_"+id).val("");
		$("#customValue_"+id).val("");
		$("#customParam_"+id).attr("readonly","");
	}
	else
	{
		$("#customParam_"+id).val(value);
		$("#customValue_"+id).val("");
		$("#customParam_"+id).attr("readonly",true);
	}
}

/********* Added by Manoj - For Video Toolbar *************/
function getVideoButtonTypes() 
{
	dropdown_options = "<option value='SystemItem'>SystemItem</option><option value='Image'>Image</option><option value='Title'>Title</option>";
	return dropdown_options;
}

function getVideoButtonSubTypes() 
{
	dropdown_options = "<option value='UIBarButtonSystemItemAction' >UIBarButtonSystemItemAction</option><option value='UIBarButtonSystemItemAdd' >UIBarButtonSystemItemAdd</option><option value='UIBarButtonSystemItemBookmarks' >UIBarButtonSystemItemBookmarks</option><option value='UIBarButtonSystemItemCamera' >UIBarButtonSystemItemCamera</option><option value='UIBarButtonSystemItemCancel' >UIBarButtonSystemItemCancel</option><option value='UIBarButtonSystemItemCompose' >UIBarButtonSystemItemCompose</option><option value='UIBarButtonSystemItemDone' >UIBarButtonSystemItemDone</option><option value='UIBarButtonSystemItemEdit' >UIBarButtonSystemItemEdit</option><option value='UIBarButtonSystemItemFastForward' >UIBarButtonSystemItemFastForward</option><option value='UIBarButtonSystemItemFixedSpace' >UIBarButtonSystemItemFixedSpace</option><option value='UIBarButtonSystemItemFlexibleSpace' >UIBarButtonSystemItemFlexibleSpace</option><option value='UIBarButtonSystemItemOrganize' >UIBarButtonSystemItemOrganize</option><option value='UIBarButtonSystemItemPause' >UIBarButtonSystemItemPause</option><option value='UIBarButtonSystemItemPlay' >UIBarButtonSystemItemPlay</option><option value='UIBarButtonSystemItemRefresh' >UIBarButtonSystemItemRefresh</option><option value='UIBarButtonSystemItemReply' >UIBarButtonSystemItemReply</option><option value='UIBarButtonSystemItemRewind' >UIBarButtonSystemItemRewind</option><option value='UIBarButtonSystemItemSave' >UIBarButtonSystemItemSave</option><option value='UIBarButtonSystemItemSearch' >UIBarButtonSystemItemSearch</option><option value='UIBarButtonSystemItemStop' >UIBarButtonSystemItemStop</option><option value='UIBarButtonSystemItemTrash' >UIBarButtonSystemItemTrash</option>";
	return dropdown_options;
}

function getVideoButtonStyles() 
{
	dropdown_options = "<option value=''>-None-</option><option value='UIBarButtonItemStyleBordered'>UIBarButtonItemStyleBordered</option><option value='UIBarButtonItemStyleDone'>UIBarButtonItemStyleDone</option><option value='UIBarButtonItemStylePlain'>UIBarButtonItemStylePlain</option>";
	return dropdown_options;
}

function getVideoButtonActions() 
{
	dropdown_options = "<option value=''>-None-</option><option value='done'>Close</option><option value='open_url'>Open URL</option><option value='play_movie'>Play New Movie</option><option value='replay'>Replay</option><option value='stop'>Stop</option>";
	return dropdown_options;
}


function changeAction(val,subtype_Id){
	switch(val.value){
		case 'open_url':
					$('#'+'toolbar_action_value_text_'+subtype_Id).css('display','block');
					$('#'+'toolbar_action_value_text_'+subtype_Id).attr('disabled',false);
					$('#'+'toolbar_action_value_'+subtype_Id).css('display','none');
					$('#'+'toolbar_show_video_'+subtype_Id).css('display','none');
					break;
		case 'play_movie':
					$('#'+'toolbar_action_value_'+subtype_Id).css('display','block');
					$('#'+'toolbar_action_value_'+subtype_Id).attr('disabled',false);
					$('#'+'toolbar_action_value_text_'+subtype_Id).css('display','none');

					$('#'+'toolbar_show_video_'+subtype_Id).css('display','block');
					break;
		default:
					$('#'+'toolbar_action_value_'+subtype_Id).attr('disabled',true);
					$('#'+'toolbar_action_value_'+subtype_Id).val('');
					$('#'+'toolbar_action_value_'+subtype_Id).css('display','none');
					
					$('#'+'toolbar_action_value_text_'+subtype_Id).attr('disabled',true);
					$('#'+'toolbar_action_value_text_'+subtype_Id).val('');
					$('#'+'toolbar_action_value_text_'+subtype_Id).css('display','block');
					
					$('#'+'toolbar_show_video_'+subtype_Id).css('display','none');
					break;
	}
}

function disableAction(val,subtype_Id){
	if(val.value=='UIBarButtonSystemItemFlexibleSpace' || val.value=='UIBarButtonSystemItemFixedSpace'){
		$('#'+'toolbar_type_action_'+subtype_Id).attr('disabled',true);
		$('#'+'toolbar_type_action_'+subtype_Id).val('');

		$('#'+'toolbar_action_value_'+subtype_Id).attr('disabled',true);
		$('#'+'toolbar_action_value_'+subtype_Id).val('');
		$('#'+'toolbar_action_value_'+subtype_Id).css('display','none');

		$('#'+'toolbar_action_value_text_'+subtype_Id).attr('disabled',true);
		$('#'+'toolbar_action_value_text_'+subtype_Id).val('');
		$('#'+'toolbar_action_value_text_'+subtype_Id).css('display','block');

		$('#'+'toolbar_show_video_'+subtype_Id).css('display','none');
	}
	else{
		$('#'+'toolbar_type_action_'+subtype_Id).attr('disabled',false);
	}

	if(val.value=='UIBarButtonSystemItemFixedSpace'){
		$('#'+'toolbar_width_value_'+subtype_Id).attr('disabled',false);
	}
	else{
		$('#'+'toolbar_width_value_'+subtype_Id).attr('disabled',true);
		$('#'+'toolbar_width_value_'+subtype_Id).val('');
	}

}

function changeSubType(val,subtype_Id)
{
	var  subtype_ele = 'toolbar_subtype_'+subtype_Id;
	
	$('#'+subtype_ele).hide();
	switch(val.value){
		case 'Image':
					$('#'+'toolbar_subtype_image_'+subtype_Id).css('display','block');
					$('#'+'toolbar_subtype_title_'+subtype_Id).css('display','none');
					$('#'+'toolbar_subtype_title_'+subtype_Id).val('');

					//$('#'+'toolbar_type_style_'+subtype_Id).css('display','block');
					$('#'+'toolbar_type_style_'+subtype_Id).attr('disabled',false);
					$('#'+'toolbar_show_image_'+subtype_Id).css('display','block');
					$('#'+'toolbar_subtype_'+subtype_Id).val('');
					$('#'+'toolbar_width_value_'+subtype_Id).attr('disabled',true);
					$('#'+'toolbar_width_value_'+subtype_Id).val('');
					break;
		case 'Title':
					$('#'+'toolbar_subtype_title_'+subtype_Id).css('display','block');
					$('#'+'toolbar_subtype_image_'+subtype_Id).css('display','none');
					$('#'+'toolbar_subtype_image_'+subtype_Id).val('');

					//$('#'+'toolbar_type_style_'+subtype_Id).css('display','block');
					$('#'+'toolbar_type_style_'+subtype_Id).attr('disabled',false);
					$('#'+'toolbar_show_image_'+subtype_Id).css('display','none');
					$('#'+'toolbar_subtype_'+subtype_Id).val('');
					$('#'+'toolbar_width_value_'+subtype_Id).attr('disabled',true);
					$('#'+'toolbar_width_value_'+subtype_Id).val('');
					break;
		
		case 'SystemItem':
					$('#'+'toolbar_subtype_title_'+subtype_Id).css('display','none');
					$('#'+'toolbar_subtype_image_'+subtype_Id).css('display','none');
					$('#'+'toolbar_subtype_title_'+subtype_Id).val('');
					$('#'+'toolbar_subtype_image_'+subtype_Id).val('');
					$('#'+'toolbar_subtype_'+subtype_Id).val('');

					//$('#'+'toolbar_type_style_'+subtype_Id).css('display','none');
					$('#'+'toolbar_type_style_'+subtype_Id).attr('disabled',true);
					$('#'+'toolbar_show_image_'+subtype_Id).css('display','none');
					$('#'+subtype_ele).show();
					break;
		default:break;
	}
}

function addNewButtonsDiv(customparDiv)
{
	countVideoButtonsDiv++;
	var code = "";
	if(countVideoButtonsDiv == 0){
		$("#CustomVideoToolbarHd").show();
		$("#CustomVideoToolbarTr").show();
	}
	code +=  "<tr>";


	var toolbarTypesOptions = getVideoButtonTypes();
	code +=  "   <td width=100><SELECT id='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Parameter]' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Parameter]' onchange=changeSubType(this,'"+countVideoButtonsDiv+"') >";
	code +=  toolbarTypesOptions;
	code +="</SELECT></td>  ";

	var type_Id = 'data[BannerInfo][Custom]['+countVideoButtonsDiv+'][Parameter]';
	type_val = 'SystemItem';
	var videoButtonSubTypes = getVideoButtonSubTypes();
	code +=  "   <td  width=170><SELECT style='width:160px' id='toolbar_subtype_"+countVideoButtonsDiv+"' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Subtype]' onchange=disableAction(this,'"+countVideoButtonsDiv+"')>";
	code +=  videoButtonSubTypes;
	//code +="</SELECT></td>  ";
	code +="</SELECT>";

	// --- Image Upload Element ---
	code +=  "   <input style='display:none' type=file id='toolbar_subtype_image_"+countVideoButtonsDiv+"' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Image]' size='14'/>";
	// --- Image Upload Element ---

	// --- Title text Element ---
	code +=  "   <input style='display:none' type=text id='toolbar_subtype_title_"+countVideoButtonsDiv+"' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Title]' size='26'/>";
	// --- Title Text Element ---
	code +="</td>  ";
	
	// --- Style dropdown Element ---
	var videoButtonStyles = getVideoButtonStyles();
	code +=  "   <td width=160><SELECT style='width:150px;' id='toolbar_type_style_"+countVideoButtonsDiv+"' NAME='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Style]' disabled=true>";
	code +=  videoButtonStyles;
	code +="</SELECT>";
	code +="</td>  ";
	// --- Style dropdown Element ---

	// --- Action Dropdown ---
	var videoButtonActions = getVideoButtonActions();
	code +=  "   <td  width=100> <SELECT style='width:90px' id='toolbar_type_action_"+countVideoButtonsDiv+"' NAME='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Action]' onchange=changeAction(this,'"+countVideoButtonsDiv+"')>";
	code +=  videoButtonActions;
	code +="</SELECT>";
	code +="</td>  ";
	// --- Action Dropdown ---

	// Action Value Fields
	code +=  "  <td width=165> <input style='display:none'  type=file id='toolbar_action_value_"+countVideoButtonsDiv+"' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Value]' size='14'/>";
	
	code +=  "   <input type=text disabled=true id='toolbar_action_value_text_"+countVideoButtonsDiv+"' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][ActionValue]' size='27'/>";

	code +="</td>";
	// Action Value Fields

	code +=  "  <td width=50> <input disabled=true type=text id='toolbar_width_value_"+countVideoButtonsDiv+"' name='data[BannerInfo][VideoCustomToolbar]["+countVideoButtonsDiv+"][Width]' size='3'/></td>";

	code +=  "   <td> <a href='#' onclick='$(this).parents(\"tr:first\").remove(); return false;' class='deleteCustParam'>&nbsp;</a></td>";
	code +=  "</tr>";
	$("#"+customparDiv).append(code);
}
/********* Added by Manoj - For Video Toolbar *************/

function displayAddGroup(spanid){

	if($('#'+spanid).css('display')== 'none'){
		$('#'+spanid).css('display','inline-block');
	}
	else{
		$('#'+spanid).css('display','none');
		$('#newgroupname').val('');
	}
}

function addCheckbox(group_name,new_group_id){ 
   var container = $('.tblbrdr'); 
   var html = '<div class=sub><input type="CHECKBOX" ID="SiteGroup_'+new_group_id+'" VALUE="1" NAME="data[SiteInfo][SiteGroup]['+new_group_id+']" checked /><label for="'+group_name+'">'+group_name+'</label></sub>';
   container.append($(html)); 
}

function addGroupName(spanid){
	groupname = $('#newgroupname').val();
	post_url = '/site/addZoneGroup/'+ urlencode(groupname);
	$.ajax({
		type:"POST",
		url:post_url,
		dataType: "json",
		success: function(msg){
			group_id = msg.group_id;
			if(group_id>0)
			{
				addCheckbox(groupname,group_id); 
				$('#'+spanid).css('display','none');
				$('#outer_div').css('display','');
				$('#group_error_msg').css('display','none');
			}
			else
			{
				$('#group_error_msg').css('display','');
				$('#group_error_msg').html(msg.message);
			}
		}
	});
}

function showHideDivs(id1, id2)
{
$("#submit_type").val(id2);
$('[name="frmReport"] #submit').click();

}

function displayAdnetworkFields(network)
{
	//alert(network);
	var site2_networks_arr = new Array('go2media','jumptap','mads','madvertise','mojiva','quattro','third screen media');
	var arr = network.split("||");
	network_name = arr[1];
	//alert(network_name);
	$("#tr_site2").hide();
	for(i=0;i<site2_networks_arr.length;i++){
		var re = "/"+site2_networks_arr[i]+"/gi";
		var myRE = new RegExp(site2_networks_arr[i], "gi");
		var match_network = network_name.match(myRE);
		//alert("match = "+match);
		if(match_network!=null)
		{
			$("#tr_site2").show();
			break;
		}
	}
}

function addNewAdvertiserMediaDiv(bannerImageDiv)
{
	countMultiImagesDivAdv++;
	var code = "";
	code +=  "<tr id='img_"+countMultiImagesDivAdv+"''>";
	code +=  "   <td> <input name='data[AdvertiserInfo][multiImages]["+countMultiImagesDivAdv+"]' value='' maxlength='255' id='data[AdvertiserInfo][multiImages]["+countMultiImagesDivAdv+"]' type='file'>";
	code +=  "   &nbsp;&nbsp;&nbsp;<a href='#' onclick=' deleteBannerImageDiv(this,"+countMultiImagesDivAdv+");return false;' class='deleteCustParam'>Delete</a>";
	code +=  " </td></tr>";

	$("#"+bannerImageDiv).append(code);
}

function displayUploadRichMedia(obj)
{
	if($("#showhide_upload").hasClass('show'))
	{
		$("#showhide_upload").removeClass('show');
		$("#display_rich_media").show();
	}
	else
	{
		$("#showhide_upload").addClass('show');
		$("#display_rich_media").hide();
	}
}

// Function called (ajax request) when user expands advertiser to display campaigns under it.
function displayCampaignsForAdvertiser(advertiser,status,classname)
{
	str_arr = advertiser.split('-');
	id = str_arr[1];
	div_id = id+'_campaigns_div';
	
	var has_id = $("#"+div_id).children().hasClass('treeTable');
	if(has_id == true)
	{
		$("#"+div_id).show();
		return;
	}

	show_ajax_wait(div_id);
	// AJAX Call - to get the campaigns of advertiser
	posturl = '/campaign/getAllCampaigns/'+id+'/'+status+'/'+classname;
	$.ajax({
		type: "POST",
		async: false,
		url: posturl,
		success: function(msg){
				//alert("message = "+msg);
				$("#"+div_id).html(msg);
			   },
		error:function(){
				$("#"+div_id).html('<table><tr><td>There was an error fetching data.Please try again.</td></tr></table>');
			}
		});
}

// Function called (ajax request) when user expands campaign to display banners under it.
function displayBannersForCampaigns(campaign,status,classname)
{
	str_arr = campaign.split('-');
	id = str_arr[2];
	clientid = str_arr[1];

	div_id = id+'_banners_div';

	var has_id = $("#"+div_id).children().hasClass('treeTable');
	if(has_id == true)
	{
		$("#"+div_id).show();
		return;
	}
	
	show_ajax_wait(div_id);

	// AJAX Call - to get the campaigns of advertiser
	posturl = '/campaign/getAllBanners/'+id+'/'+clientid+'/'+status+'/'+classname;
	$.ajax({
		type: "POST",
		async: false,
		url: posturl,
		success: function(msg){
				$("#"+div_id).html(msg);
			   },
		error:function(){
				$("#"+div_id).html('<table><tr><td>There was an error fetching data.Please try again.</td></tr></table>');
			}
		});
}

function getAndShowHideReport(id_show, id_hide)
{
	var zone_id=$("#zoneId").val();
	var start_date = $("#startdate").val();
	var end_date = $("#enddate").val();
	var posturl = '/addetails/sitewise_GBD';
	if (id_show == 'group_by_site_report')
	{
		posturl = '/addetails/sitewise_GBS';
	}
	var postdata = "zone_ids="+zone_id+"&startdate="+start_date+"&enddate="+end_date;
	var done = $("#"+id_show).attr("rel");
	if (done != 'done')
	{
		show_ajax_wait(id_show+"_div");
		$.ajax({
			type: "POST",
			url: posturl,
			data: postdata,
			success: function(msg)
			{
					$("#"+id_show+"_div").html(msg);
					admarvel_table_sort();
			},
			error: function(msg){
				$("#"+id_show).html('<table><tr><td>There was an error fetching data.Please try again.</td></tr></table>');
			}
		});
	}
		
	$("#"+id_hide+"_href").removeClass('current');
	$("#"+id_show+"_href").addClass('current');
	$("#"+id_hide).hide();
	$("#"+id_show).show();
	$("#group_by").val(id_show);
}




function getReportAndShowHideReportForMultiple(id_show, id_hide1, id_hide2, id_hide3, id_hide4, id_hide5)
{
	//First get the report.
	var zone_id=$("#zoneId").val();
	var start_date = $("#startdate").val();
	var end_date = $("#enddate").val();
	var network_ids=$("#adnetwork_options").val();
	var postdata = "zone_ids="+zone_id+"&startdate="+start_date+"&enddate="+end_date+"&network_ids="+network_ids;
	var posturl = '';
	if (id_show == 'group_by_date_report3')
		 posturl = '/addetails/networkwise_GBD/';
	else if (id_show == 'group_by_campaign_report3')
		posturl = '/addetails/networkwise_GBC/';
	else if (id_show == 'group_by_banner_report3')
		posturl = '/addetails/networkwise_GBB/';
	else
	{
		posturl = '/addetails/networkwise_GBA/';
		postdata += "&network_ids="+$("#adnetwork_options").val();
	}
	var done = $("#"+id_show).attr("rel");
	if (done != 'done')
	{
		show_ajax_wait(id_show+"_div");
		$.ajax({
			type: "POST",
			url: posturl,
			data: postdata,
			success: function(msg)
				{
						
						$("#"+id_show+"_div").html(msg);
						admarvel_table_sort();
				},
			error: function(msg){
			$("#"+id_show).html('<table><tr><td>There was an error fetching data.Please try again.</td></tr></table>');
			}
			});
	}
	var new_id_show = id_show+"_href";
	var new_id_hide1 = id_hide1+"_href";
	var new_id_hide2 = id_hide2+"_href";
	var new_id_hide3 = id_hide3+"_href";
	var new_id_hide4 = id_hide4+"_href";
	var new_id_hide5 = id_hide5+"_href";

	$("#"+new_id_show).addClass('current');
	$("#"+new_id_hide1).removeClass('current');
	$("#"+new_id_hide2).removeClass('current');
	$("#"+new_id_hide3).removeClass('current');
	$("#"+new_id_hide4).removeClass('current');
	$("#"+new_id_hide5).removeClass('current');

	$("#"+id_hide1).hide();
	$("#"+id_hide2).hide();
	$("#"+id_hide3).hide();
	$("#"+id_hide4).hide();
	$("#"+id_hide5).hide();
	$("#"+id_show).show();
	$("#group_by").val(id_show);
}


function hide_show(report_type){
	div_id = report_type+'_div';
	href_id = report_type+'_href';
	$("[id*=_div]").css('display', 'none');    
	$("#"+div_id).show();
	
	$("[id*=_href]").removeClass('current');
	$("#"+href_id).addClass('current');
	$("#group_by").val(report_type);
}

function displayAddetailsCampaignsTabReportByAjax(startdate,enddate,date_options,zoneId,campaign_options,advertiser_options,report_type,submit_type_ajax)
{
	report_function='campaign_reports';
	div_id = report_type+'_div';
	var id = $("#"+report_type).attr('id');
	if(id != undefined)
	{
		hide_show(report_type);
		return;
	}
	hide_show(report_type);
	show_ajax_wait(div_id);
	
	
	posturl = "/addetails/campaign_reports/"
	postdata = "startdate="+startdate+"&enddate="+enddate+"&date_options="+date_options+"&zoneId="+zoneId+"&campaign_options="+campaign_options+"&advertiser_options="+advertiser_options+"&report_type="+report_type+"&submit_type_ajax="+submit_type_ajax;
	$.ajax({
		type: "POST",
		url: posturl,
		data: postdata,
		success: function(msg){
				hide_show(report_type);
				//window[report_type] = true;
				$("#"+div_id).html(msg);
				admarvel_table_sort();
			   },
		error:function(){
				$("#"+div_id).html('<table><tr><td>There was an error fetching data.Please try again.</td></tr></table>');
			}
		});
	$("#group_by").val(report_type);
}

function show_ajax_wait(id)
{
	$("#"+id).html("<table align='center'><tr><td><img src='/img/ajax-loader-alloc.gif' alt='Loading data...'/></td></tr></table>");
}

// This function is used for AJAX call on Admarvel UI Home page.It groups by site/date 
function getReportAndShowHideReport(id_show, id_hide, columnName, affiliateid)
{
	var zone_id=$("#zoneId").val();
	var start_date = $("#startdate").val();
	var end_date = $("#enddate").val();
	var posturl = '/homepage/homepage_gbd';
	if (id_show == 'group_by_site_report')
	{
		posturl = '/homepage/homepage_gbs';
	}
	var postdata = "zone_ids="+zone_id+"&startdate="+start_date+"&enddate="+end_date+"&columnName="+columnName+"&affiliateId="+affiliateid;
	var done = $("#"+id_show).attr("rel");
	if (done != 'done')
	{
		show_ajax_wait(id_show+"_div");
		$.ajax({
			type: "POST",
			url: posturl,
			data: postdata,
			success: function(msg)
			{
					$("#"+id_show+"_div").html(msg);
					admarvel_table_sort();
			},
			error: function(msg){
				$("#"+id_show).html('<table><tr><td>There was an error fetching data.Please try again.</td></tr></table>');
			}
		});
	}
	else{
		admarvel_table_sort();
	}
		
	$("#"+id_hide+"_href").removeClass('current');
	$("#"+id_show+"_href").addClass('current');
	$("#"+id_hide).hide();
	$("#"+id_show).show();
	$("#group_by").val(id_show);
}