/*
This is the URL where the page will redirect to 
Set this to blank to remove redirect
You can use full URL in format http://www.the-dma.org/
Or you can use relative URL in format /dm-essentials/coursename.php
*/
var callMeRedirectURL = "http://test.dmaeducation.org/ThankYou.php";


function sendToFriend() {
	var url = document.URL;
	var rec = $('#friend_email').val();
	var data = "url="+url+"&rec="+rec;
	
	$.ajax({
		data: data,
		type: 'post',
		url: '/sendToFriend.php',
		success: function(res) {
			if(res)
				$('#send_btn').append(res);
			else
				$('#send_btn').html('Thank you');
		}
	});
}

function validateFields() {
	
	var valid = true;
	 
	 $('.text_input').removeClass('input_focus');
	 $('.text_input').parent().parent().children().removeClass('input_focus');
		
	$('#reg_content .text_input').each(function(){
		
		if (this.value == this.defaultValue || this.value=='') {
			$(this).addClass('input_err');
			$(this).parent().parent().children().addClass('input_err');
			valid = false;
			
			
		} else {
			$(this).removeClass('input_err');
			$(this).parent().parent().children().removeClass('input_err');

			if ($(this).attr('id')=='txtEmail') {
				var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	
				var address = this.value;
				
				if(reg.test(address)==false) {
					$(this).addClass('input_err');
					$(this).parent().parent().children().addClass('input_err');
					valid = false;
				}
			}
		}
	});
	return valid;
}

//This functino builds the data string
function sendLeadData() {
	var dstring = null; 
	$('#reg_content').find('input').each(function() {
		if($(this).attr('type') == 'button')
			return false;
		if(dstring)
			dstring = dstring + "&"+$(this).attr('id')+"="+$(this).val();
		else
			dstring = $(this).attr('id')+"="+$(this).val();
	});
	$('#reg_content').find('select :selected').each(function() {
		var clean = $(this).text();
		clean = clean.replace(/&/g, 'and');
		dstring = dstring + "&"+$(this).parent().attr('id')+"="+clean;
	});
	return dstring;
}


//This function handles mailing
function sendLead(data) {
	var msg;
	$.ajax({
		data: data,
		type: 'post',
		url: '/sendlead.php',
		async: false,
		success: function(res) {
			msg = res;
		}
	});
	return msg;
}
		
//This function applies a negative left margin to the front page right col
function homePageRCol() {
	var fprcolW = $('#fprcol').width();
	$('#fprcol').css({'margin-left':'-'+fprcolW+'px'});
}

function showDCMP() {
		
		if ($('#popup_wrapper:visible').length>0) {
				
			$('#popup_wrapper').fadeOut(150, function(){
				
				$('#dim_bg').hide();
				
				$('#popup_wrapper').fadeIn(150);
				$('.pop').fadeOut(0);
				$('#popup_dma').fadeIn(0);
				$('#blue_one').css({height:$('#blue_two').height()+'px'});
				$('#popup_dma').css({marginTop:$(window).scrollTop()+20+'px'});	
				$('#popup_dma_shadow .drop_shadow_body').css({height:$('#popup_dma').height()-10+'px'});										  
														  
			
			});
			
		} else {
			
			$('#dim_bg').hide();
			
			$('#popup_wrapper').fadeIn(150);
			$('.pop').fadeOut(0);
			$('#popup_dma').fadeIn(0);
			$('#blue_one').css({height:$('#blue_two').height()+'px'});
			$('#popup_dma').css({marginTop:$(window).scrollTop()+20+'px'});	
			$('#popup_dma_shadow .drop_shadow_body').css({height:$('#popup_dma').height()-10+'px'});
		
		}
		
		return false;
	};
	

var begin;
var num_two;

function monkeyPatchAutocomplete() {

	 var oldFn = $.ui.autocomplete.prototype._renderItem;

	 $.ui.autocomplete.prototype._renderItem = function( ul, item) {

	  var arr = item.label.split('type=');
	  
	  var t = arr[0];
	  
	  item.value = t;
	  
	  var arr2 = arr[1].split('cat=');
	  
	  var s = parseInt(arr2[0]);
	  
	  var arr3 = arr2[1].split('link=');
	  
	  var c = arr3[0];
	  
	  var url = arr3[1];
	  
	  var tag;
	  
	  switch(s) {
		case 1:  tag='tag_90.gif'; break;
		case 2:  tag='tag_onlineinperson.gif'; break;
		case 3:  tag='tag_inperson.gif'; break;
		default: tag='tag_online.gif';
	  }
	  
	  var img = ' <img src="/images/'+tag+'"/> ';
	  
	
	  var head ='';
	  
	  if (c=='Topics ') {

		  img='';
	  }
	  
	  if (begin!=c) {
		$( '<li class="cat_header">'+c+'</li>' ).appendTo( ul );
		begin=c;
		num_two=0;
	  }
	 
	 num_two++;	   
		
	 if( num_two<=3) { 
		 $( "<li></li>" )
				  .data( "item.autocomplete", item )
				  .append( '<a href="/'+url+'" >' + t +img+'</a>' )
				  .appendTo( ul );
		  };
	 }
		  
		
}

$(document).ready(function() {
	homePageRCol();
	$("select, input:checkbox, input:radio, input:file").uniform();

	$('.show_vid').click(function(){
								  
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		
		var isiPod = navigator.userAgent.match(/iPod/i) != null;
		
		var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
		
		if (isiPad==true) {
			
			window.location = '/videos/DMA_Final_Web_low.mov';
		}
		else if (isiPod==true || isiPhone==true) {
			
			window.location = '/videos/DMA_Final_Web.m4v';
		}
		else {
			//Show the video here
				var flashvars = {};
				flashvars.vidURL = "/videos/DMA_Final_Web.flv";     // <<== set the path to the video here
				var params = {};
				params.play = "true";
				params.menu = "false";
				params.quality = "high";
				params.scale = "noscale";
				params.salign = "tl";
				params.wmode = "transparent";
				params.allowfullscreen = "false";
				params.allowscriptaccess = "sameDomain";
				var attributes = {};
				attributes.id = "video";
				attributes.align = "top";
				$.fancybox({
					//content: "<div id='video_wrapper'><div id='video'></div><div id='share_vid'><div id='share_left'></div><div id='share'>_</div><div id='share_right'></div></div>",
					content: "<div id='video_wrapper'> \
      \
                <div id=\"video\">&nbsp; \
                  <a href=\"http://www.adobe.com/go/getflashplayer\"> \
                        <img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" /> \
                    </a> \
                </div> \
      \
                <div class=\"clear_float\"></div> \
      \
                <div id=\"share_vid\"> \
                    <div id=\"share\"><img src=\"/images/share_txt.gif\"/>  \
      \
      \
                     <a href=\"http://www.facebook.com/sharer.php?u=http://dmaeducation.org/?84\" target=\"_blank\"><img src=\"/images/share_facebook.gif\"/> </a> \
      \
                        <a href=\"http://twitter.com/home?status=http://dmaeducation.org/ : Join the DMA Community – Converse today about the direct marketing developments of tomorrow.\" target=\"_blank\"><img src=\"/images/share_twitter.gif\"/></a>  \
      \
                        <a href=\"http://digg.com/submit?url=http://dmaeducation.org/\" target=\"_blank\"><img src=\"/images/share_digg.gif\"/> </a> \
      \
                        <a href=\"http://www.reddit.com/submit?url=http://dmaeducation.org/\" target=\"_blank\"><img src=\"/images/share_reddit.gif\"/></a> \
      \
                    </div> \
                </div> \
      \
            </div>",
					padding: "0px",
					width: "932px"
				});
				swfobject.embedSWF("/flash/DMAVideoPlayer.swf", attributes.id, "940", "565", "9.0.0", false, flashvars, params, attributes)
			}
		return false;  
		
	});

	//perform some course list actions when the field is changed
	$('#ddlTopic').change(function() {
		var options = '';
		var catId = $(this).val();
		var arr = getCourses(catId);
		if(typeof(arr) == 'object') {
			for(var item in arr) {
				var desc = arr[item][0];
				var link = arr[item][1];
				if(typeof(desc) != 'undefined')
					options = options+"<option value='"+link+"'>"+desc+"</option>\n";
			}
		}
		$('#course_list').html(options);
		$.uniform.update();
	});	

	$('#call_me_btn, #contact_btn').click(function() {
		if(validateFields()) {
			var data = sendLeadData();
			var res = sendLead(data+"&sub=Call Me");
			if(res) {
				$.fancybox({
					'content' : res
				});
			} else {
				if(callMeRedirectURL)
					window.location = callMeRedirectURL;
				$('#show_reg').fadeOut(500, function() {
					$('#show_thanks').fadeIn(500);
				});
			}
		}
	});

	$('#register_btn').click(function() {
		if(validateFields()) {
			var data = sendLeadData();
			var res = sendLead(data+"&sub=DMA");
			if(res) {
				$.fancybox({
					'content' : res
				});
			} else {
				var url = $('#course_list :selected').val();
				if(url != 'Course' && url != '')
					window.location = url;
			}
		}
	});

	var bshide = 1;

	$('#registration_box').click(function() {
		bshide = 0;
		setTimeout(function() {
			bshide = 1;
		}, 500);
	});

	$('.black_src').click(function(){
		if(bshide == 1) {
			$('.black_src').hide();
			$('#notice').fadeOut(150);
		}
	});
	
	$('#print_btn').click(function(){
		window.open($(this).attr('print'));
	});	  
	
	$('#submit_btn_pop').click(function(){
		sendToFriend();
	});
	
	$('.register_btn_pop').click(function(){
		//Get current URL to find course
		var urlArr = (document.URL).split('/');
		var topic = urlArr[3].replace(/-/g, ' ').toLowerCase().substring(0,6);
		//Special fix for how web analytics is titled
		if(topic.match(/^web an/))
			topic="analyt";
		var course = urlArr[4].replace(/-/g, ' ').replace(/.php$/, '').toLowerCase();
		var courseH1 = $('h1').first().html();
		if(courseH1)
			courseH1 = courseH1.replace(/-|\(|\)| /g, '').toLowerCase();
		
		$('#ddlTopic').find('option', this).each(function() {
			var name = $(this).text().toLowerCase();
			if(name.match(topic))
			{
				$(this).attr({'selected':'selected'});
				$('#ddlTopic').change();
			}
		});

		$('#course_list').find('option', this).each(function() {
			var name = $(this).text().replace(/&/g, '&amp;').replace(/-|\(|\)| /g, '').toLowerCase();
			if(name.match(course) || name.match(courseH1))
			{
				$(this).attr({'selected':'selected'});
				$('#course_list').change();
			}
		});
	
		$.uniform.update();
										  
		 $('#txtFName').focus();
		 
		 if ($(window).height()<$('body').height()) {
			$('#main_blk_bg').css({height:$('body').height()+'px'});
		 }
		
		 $('.black_src').show();
		 $('#notice').fadeIn(150);
		
		 
		 window.scrollTo(0,0);
	
	});

	 monkeyPatchAutocomplete();

	 $("input#search_courses").autocomplete({
		minLength: 2,
		delay: 100,
		source:function(){

		$.get('/course/query.php', function(data) {
				
				var opts = [];
				
				var pre = '';
				
				$.each(data.Certifications, function(i, v){
													 
					pre = typeof v.TopicName != 'undefined' ? v.TopicName+': ' : '';
					opts.push(pre+v.Name+' type='+v.CategoryId+' cat=Certifications link='+v.Url+'.php');	
				
				});	

				$.each(data.Courses, function(i, v){
					pre = typeof v.TopicName != 'undefined' ? v.TopicName+': ' : '';						  
					opts.push(pre+v.Name+' type='+v.CategoryId+' cat=Courses link='+v.Url+'.php');	
				
				});
				
				
				$.each(data.Topics, function(i, v){
					pre = typeof v.TopicName != 'undefined' ? v.TopicName+': ' : '';
					opts.push(pre+v.Name+' type='+v.CategoryId+' cat=Topics link='+v.Url+'.php');	
				
				});
				
				begin = '';
				num_two=0;
				
				$("input#search_courses").autocomplete( "option", "source", opts );
			});

		},
		select: function(event, ui) {
			var str = ui.item.label.split('link=')[1];
			window.location = '/'+str;
		}
					
	 });
	 
	$("input#search_courses").keypress(function(event) {
			if (event.keyCode == '13') {
		//	 searchThis();
			}
	});
	
	$('#search_left').click(function(){
		//searchThis();							 
	
	});

/*	function searchThis(){
		window.location = '/course/search?q='+$("input#search_courses").val();
	};*/
	
	$('.showDCMP').click(function() {
		showDCMP();
	});

	/* Position the menu */
	var snX = $('#navigation').offset().left;
	var snY = $('#navigation').offset().top + 40;
	$('.subnav').css({'left':snX, 'top':snY});

	/*IE7 fix for nbsp in menu*/
	$('.link').find('a').each(function() {
		var newHtml = $(this).html().replace(/\t|\r|\n|\W| /, '&nbsp;');
		$(this).html(newHtml);
	});

});

