/*
@Authors: Eli Horne, G. Richard Bellamythx.inputClear(
@Requirements: jQuery 1.3 or greater
*/

if (typeof (thx) == "undefined") {
	thx = {};
}

String.IsNullOrEmpty = function(value) {
	var isNullOrEmpty = true;
	if (value) {
		if (typeof (value) == 'string') {
			if (value.length > 0)
				isNullOrEmpty = false;
		}
	}
	return isNullOrEmpty;
}

/**
* Concatenates the values of a variable into an easily readable string
* by Matt Hackett [scriptnode.com]
* @param {Object} x The variable to debug
* @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
* @param {String} sep The separator to use between [default: a single space ' ']
* @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
*/
function print_r(x, max, sep, l) {

	l = l || 0;
	max = max || 10;
	sep = sep || ' ';

	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}

	var 
		i,
		r = '',
		t = typeof x,
		tab = '';

	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {
		l++;
		for (i = 0; i < l; i++) {
			tab += sep;
		}
		if (x && x.length) {
			t = 'array';
		}
		r += '(' + t + ") :\n";
		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch (e) {
				return "[ERROR: " + e + "]\n";
			}
		}
	} else {
		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}
		r += '(' + t + ') ' + x + "\n";
	}

	return r;
};
var_dump = print_r;


thx.dropDowns = function() {

	/*
	@Brief:	cross-browser suckerfish dropdowns with active state
	*/

	$('.drop').hover(function() {

		// vars
		$this = $(this);
		$dropdown = $this.find('.sub-nav');

		// Kill any other dropdowns
		$('.nav li').removeClass('hover');

		// Show this one
		$this.addClass('hover');

		// On roll-off
	}, function() {
		// Kill it
		$this.removeClass('hover');
	});

	$('.sub-nav').each(function(i) {
		$(this).find('ul li a:first').hide();
	});
};

thx.sectionDetect = function() {

	/*
	@Brief:	Determines the current section via the URL and passes body classes
	*/

	var urlGlobal = window.location.href;
	var urlSection = urlGlobal.split("/");

	if (urlSection[3].length) {
		$('body').addClass('section-' + urlSection[3]);
		if (urlSection[4]){
			if (urlSection[4].length) {
				$('body').addClass('subsection-' + urlSection[4]);
			};
		}
	};

};

thx.sectionTabs = function() {

	/*
	@Brief:	Currents "sub level" navigation active states
	*/

	$('.section-tab-nav ul li a:first').hide();
	$('.section-tab-nav li li').each(function() {
		//var subnavClass = $(this).text();
		var subClass = $(this).text().replace(/ /g, '-').toLowerCase();
		var safeSubClass = 'subsection-' + subClass;
		$(this).addClass(safeSubClass);
		
		if ($('body').hasClass(safeSubClass)) {
			$(this).addClass('active');
		} 		
		if (safeSubClass == 'subsection-thx-technology' && $('body').hasClass('subsection-thx-technology-professional')){
			$(this).addClass(safeSubClass);
			$(this).addClass('active');
		} 
	});

	thx.checkBrowser();
};

thx.checkBrowser = function() {

	/*
	@Brief:	Detect IE6, present upgrade message
	*/

	var COOKIE_NAME = 'thx_support';

	if (typeof document.body.style.maxHeight === "undefined") {
		if ($.cookie(COOKIE_NAME) == null) {
			$('.c-wrap').prepend('<div id="ie-error"><a class="go-away">Don\'t Show Again</a><div class="title">We Noticed You Are Using Internet Explorer 6</div><div class="copy">We detected your browser is out of date. For the best possible experience upgrade to the <a target="_blank" href="http://www.microsoft.com/windows/downloads/ie/">latest version of Internet Explorer</a>, or try one of these fine browsers: <a target="_blank" href="http://www.getfirefox.com/">Firefox</a>, <a target="_blank" href="http://www.apple.com/safari/download/">Safari</a>, <a target="_blank" href="http://google.com/chrome/">Chrome</a>.');
		}
	} else { };

	$('.go-away').click(function() {
		$('#ie-error').slideUp('slow');
		$.cookie(COOKIE_NAME, 'nag me not');
	});
};

thx.trailerLibrary = function() {

	/*
	@Brief:	Controls the "trailers" section
	*/

	var curUrl = window.location.pathname;
	var curId = curUrl.split("/");
	var curVid = '#' + curId[curId.length - 1];
	$(curVid).addClass('active');

	var curTitle = $('.trailer-library li.active').find('h3 a').text();
	$('#thx-trailer h2').text(curTitle);

	$('title').html('Consumer &#171; Movies &#171; ' + curTitle + ' &#171; THX.com');
	
};

thx.podGlow = function() {

	/*
	@Brief: Creates the classes so that a layered "glow" can be applied to each feature pod
	*/

	$('.features .pod').each(function(podInt) {
		if (podInt == 0) {
			$(this).addClass('first');
		};

		if (podInt == 1) {
			$(this).addClass('second');
		};

		if (podInt == 2) {
			$(this).addClass('third');
		};

		if (podInt == 3) {
			$(this).addClass('fourth');
		};
	});
};

thx.techFilter = function() {

	/*
	@Brief:	Filter THX Technology by category
	*/

	$('#thx-tech-filter .nav input').each(function() {
		$(this).attr('checked', 'check');
	});
	$('#thx-tech-filter .nav input').click(function() {
		var toggleClass = '.' + $(this).attr('class');
		if ($(this).is(':checked')) {
			$('#thx-tech-filter .results').find(toggleClass).animate({ 'opacity': '1' }, 500);

		} else {
			$('#thx-tech-filter .results').find(toggleClass).animate({ 'opacity': '0.25' }, 500);
		};
	});

};


thx.miniTabs = function() {

	/*
	@Brief: Common tab utility used on internal components
	*/

	nav = $('.mini-tab').find('.tabs');
	nav.find('li:first').addClass('active');
	$('.panel').hide();
	$('.panel:first').show();

	$('.tabs li').click(function() {
		$(this).addClass('active').siblings().removeClass('active');
		var targetPanel = $(this).find('a').attr('href');
		$('.panel:visible').hide();
		$(targetPanel).show();
		return false;
	});
};

thx.shareThis = function() {

	/*
	@Brief:	Enables sharing via twitter and facebook
	*/

	var currentUrl = encodeURIComponent(window.location.href);
	var currentTitle = encodeURIComponent(document.title);
	var fbText = '?u=' + currentUrl + '&t=' + currentTitle;
	var maxLength = 140 - (currentUrl.length + 1);

	if (currentTitle.length > maxLength) {
		currentTitle = currentTitle.substr(0, (maxLength - 3)) + '...';
	};

	var fbShare = 'http://www.facebook.com/sharer.php' + fbText;
	var twtShare = 'http://twitter.com/home?status=Reading:%20' + currentTitle + ' ' + currentUrl;

	$('#fbShare').attr('href', fbShare);
	$('#twtShare').attr('href', twtShare);


};

thx.hoverHelp = function(element) {

	/*
	@Brief:	Modular hover helper, used in Certified Releases
	*/

	var ele = $(element);
	$(ele + ':nth-child(3n)').addClass('last');
	ele.hover(function() {
		ele.find('.hover').hide();
		$(this).stop().find('.hover').fadeIn('fast');
	}, function() {
		$(this).find('.hover').fadeOut('fast');
	});

};

thx.podsPagination = function(type) {

	/*
	@Brief:	Upgrade pods pagination to better human messaging. 
	*/

	//alert('type = ' + type);
	var uriStructure = $.deparam.querystring();
	uriStructure['type'] = type;
	//alert('uriStructure = ' + uriStructure.toString());

	var firstPage = $('.pager .pageNum:first');
	var currentPage = $('.pager .currentPage');
	var lastPage = $('.pager .pageNum:last');
	var nextToLast = $(lastPage).prev();

	$('.pager a').each(function() {
		if (parseInt($(this).text() - $(this).prev().text()) > 1) {
			$(this).before('<span class="elip">...</span>');
		}
	});

	if (currentPage.text() == '1') {
		$('.pager').prepend('<span class="previous disabled">&laquo; Previous</span>');
	} else {
		uriStructure['pg'] = parseInt(currentPage.text() - 1);
		$(firstPage).before('<a class="previous" href="' + $.param.querystring('', uriStructure) + '">&laquo; Previous</span>');
		delete uriStructure['pg'];
	};

	if (currentPage.text() == lastPage.text()) {
		$('.pager').append('<span class="next disabled">Next &raquo;</span>');
	} else {
		uriStructure['pg'] = parseInt(parseInt(currentPage.text()) + 1);
		$('.pager').append('<a class="next" href="' + $.param.querystring('', uriStructure) + '">Next &raquo;</span>');
	};

};

thx.certifiedReleases = function() {

	/*
	@Brief:	Certified Releases layout control
	*/

	var COOKIE_NAME = 'thx_layout';

	if ($.cookie(COOKIE_NAME) == null || $.cookie(COOKIE_NAME) == 'release_icon') {
		makeIcon();
	} else {
		makeList();
	};

	$('#release-list').click(function() {
		$.cookie(COOKIE_NAME, 'release_list');
		$('#release-icon').attr('checked', false);
		makeList();
	});

	$('#release-icon').click(function() {
		$.cookie(COOKIE_NAME, 'release_icon');
		$('#release-list').attr('checked', false);
		makeIcon();
	});

	function makeList() {
		$('#release-list').attr('checked', true);

		if ($('table.list').length) {
			$('table.list').show();
			$('ol.result-items').hide();
		} else {

			var tableOpen = '<table class="list tablesorter" cellspacing="1">' +
				'<thead><tr>' +
				'<th class="col-1 header">Title</th>' +
				'<th class="col-2 header">Format</th>' +
				'<th class="col-3 header">Year</th>' +
				'<th class="col-4 header">Release Company</th>' +
				'<th class="col-5 header">Territory</th>' +
				'<th class="col-6 header">Region</th>' +
				'</tr></thead>' +
				'<tbody></tbody>' +
				'</table>';

			$('.description.post').after(tableOpen);
			$('ol.result-items').hide();
			$('.results').prepend();

			$('.result-items .item').each(function() {
				var title = $(this).find('.title').text();
				var format = $(this).find('.type').text();
				var year = $(this).find('.year span').text();
				var releaseCompany = $(this).find('.release-co span').text();
				var territory = $(this).find('.territory span').text();
				var region = $(this).find('.region span').text();

				$('.results tbody').append('<tr><td>' + title + '</td><td>' + format + '</td><td>' + year + '</td><td>' + releaseCompany + '</td><td>' + territory + '</td><td>' + region + '</td></tr>');
			});

			$("table.list").tablesorter();
		};
	};

	function makeIcon() {
		$('#release-icon').attr('checked', true);
		$('table.list').hide();
		$('ol.result-items').show();
	}
};

thx.inputClear = function(element, defaultText) {

	/*
	@Brief:	clears input fields on focus, restores on blur
	*/

	// Store the element
	var ele = $(element);

	ele.each(function() {

		// Store the default value
		if (defaultText == null)
			defaultText = ele.val();

		// Store the parent form's ID
		var parentForm = ele.parents('form');

		// Click the input field
		ele.focus(function() {

			// If it matches the default value, clear the input field
			if ($(this).val() == defaultText) {
				$(this).val('');
			};

			// As you leave, restore the default text if the field is empty
			$(this).blur(function() {
				if ($(this).val().length < 1) {
					$(this).val(defaultText);
				};
			});
		});

		// When you submit the form
		parentForm.submit(function() {

			// If the value matches the default
			if (ele.val() == defaultText) {

				// Clear the input field and send the focus there. User friendly!
				ele.val('').focus();

				// Don't submit the search
				return false
			} else {

				// Otherwise, submit like crazy
				return true;
			}
		});
	});
};

thx.map = function(centerAddress, latitude, longitude) {

	/*
	@Brief:	Builds the results map
	*/

	var map = new GMap2($('#results-map').get(0));
	var results = false;
	if (latitude != null) {
		var center = new GLatLng(latitude, longitude);
		bounds = new GLatLngBounds();
		map.setCenter(center, 8);
		map.setUIToDefault();
		var itemSelector = $('li.result-item').length != 0 ? 'li.result-item' : 'li.result-item2';
		$(itemSelector).each(function() {
			var coordinates = $('.coordinates', this).text().split(',');
			var point = new GLatLng(coordinates[0], coordinates[1]);
			var marker = thx.createMarker(centerAddress, map, point, $(this));
			map.addOverlay(marker);
			bounds.extend(marker.getPoint());
			var descSelector = $('.result-desc', this).length != 0 ? '.result-desc' : '.results-container';
			$(descSelector, this).click(function() {
				$(this).addClass('active');
				thx.displayInfoWindow(centerAddress, map, marker, $(this));
			});
			results = true;
		});
		if (results) {
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
		}
	} else {
		var center = new GLatLng(37.0625, -97.6771);
		map.setCenter(center, 4);
	}
};

thx.createMarker = function(centerAddress, map, point, element) {

	/*
	@Brief:	Creates the map markers.
	*/

	var marker = new GMarker(point);
	GEvent.addListener(marker, 'click', function() {
		thx.displayInfoWindow(centerAddress, map, marker, element);
	});
	return marker;
};

thx.displayInfoWindow = function(centerAddress, map, marker, element) {

	/*
	@Brief:	Builds and displays the map info window
	*/

	map.panTo(marker.getLatLng());
	//alert(element.html());
	var name = $('.name', element).text();
	//alert(name.toString());
	var address1 = $('.address-1', element).text();
	//alert(address1.toString());
	var address2 = $('.address-2', element).text();
	//alert(address2.toString());
	var html = '<div class="infowindow"><b>' + name + '</b>';
	if (!String.IsNullOrEmpty(address1)) {
		html += '<span class="address">' + address1 + '</span>'
	}
	html += '<span class="address">' + address2 + '</span>';
	html += '<a href="http://maps.google.com/maps?saddr=' + encodeURIComponent(centerAddress) + '&daddr=' + encodeURIComponent(address1 + ' ' + address2) + '" target="_blank">Get Directions<\/a></div>';
	
	marker.openInfoWindowHtml(html);
	
};

thx.productFinderWidget = function(manufacturer, productType, category) {

	/*
	@Brief:	Inside the widget product finder iframe - calls out to parent
	*/

	window.parent.thx.productFinderWidgetForm(manufacturer, productType, category);
}

thx.productFinderWidgetForm = function(manufacturer, productType, category) {

	/*
	@Brief:	Called from child product finder iframe, sets the widget hidden form fields.
	*/

	if (!String.IsNullOrEmpty(manufacturer)) {
		document.getElementById('manufacturer').value = manufacturer;
	} else {
		document.getElementById('manufacturer').value = null;
	}
	if (!String.IsNullOrEmpty(productType)) {
		document.getElementById('productType').value = productType;
	} else {
		document.getElementById('productType').value = null;
	}
	if (!String.IsNullOrEmpty(category)) {
		document.getElementById('category').value = category;
	} else {
		document.getElementById('category').value = null;
	}
}

thx.productFinder = function(manufacturer, productType, category) {

	/*
	@Brief:	Inside the product finder iframe - calls out to parent
	*/

	window.parent.thx.productIFrameSelector(manufacturer, productType, category);
};

thx.productIFrameSelector = function(manufacturer, productType, category) {

	/*
	@Brief:	Called from child product finder iframe, refreshes unselected criteria iframes
	*/

	manufacturer = manufacturer || '0';
	productType = productType || '0';
	category = category || '0';

	$('iframe.manufacturer').attr('src', '/product-finder-iframe/?frame=manufacturer&filter=' + manufacturer);
	$('iframe.type').attr('src', '/product-finder-iframe/?frame=type&filter=' + productType);
	$('iframe.category').attr('src', '/product-finder-iframe/?frame=category&filter=' + category);
};

thx.productManufacturer = function(manufacturer) {

	/*
	@Brief:	Manages the call from the product manufacturer iframe to the parent
	*/

	$('#M' + manufacturer).addClass('active');
	$('#M' + manufacturer).siblings().removeClass('active');

	$('li').click(function() {
		var manufacturer = $(this).attr('id').replace('M', '');
		//alert('manufacturer = ' + manufacturer);
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
		window.parent.thx.productManufacturerClick(manufacturer);
	});
};

thx.productType = function(productType) {

	/*
	@Brief:	Manages the call from the product type iframe to the parent
	*/

	$('#T' + productType).addClass('active');
	$('#T' + productType).siblings().removeClass('active');

	$('li').click(function() {
		var productType = $(this).attr('id').replace('T', ''); ;
		//alert('productType = ' + productType);
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
		window.parent.thx.productTypeClick(productType);
	});
};

thx.productCategory = function(category) {

	/*
	@Brief:	Manages the call from the product category iframe to the parent
	*/

	$('#C' + category).addClass('active');
	$('#C' + category).siblings().removeClass('active');

	$('li').click(function() {
		var category = $(this).attr('id').replace('C', '');
		//alert('category = ' + category);
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
		window.parent.thx.productCategoryClick(category);
	});
};

thx.productManufacturerClick = function(manufacturer) {

	/*
	@Brief:	Creates the call to the product iframe. Called from child iframe.
	*/

	if (manufacturer != null) {
		//alert('manufacturer = ' + manufacturer);
		var src = $.deparam.querystring($('body').find('iframe.product').attr('src'));
		if (manufacturer == '0') {
			delete src['manufacturer'];
		} else {
			src['manufacturer'] = manufacturer;
		}
		//alert($.param.querystring('/product-finder-iframe/?', src));
		$('body').find('iframe.product').attr('src', $.param.querystring('/product-finder-iframe/?', src));
	}
	return false;
};

thx.productTypeClick = function(productType) {

	/*
	@Brief:	Creates the call to the product iframe. Called from child iframe.
	*/

	if (productType != null) {
		//alert('productType = ' + productType);
		var src = $.deparam.querystring($('body').find('iframe.product').attr('src'));
		if (productType == '0') {
			delete src['productType'];
		} else {
			src['productType'] = productType;
		}
		//alert($.param.querystring('/product-finder-iframe/?', src));
		$('body').find('iframe.product').attr('src', $.param.querystring('/product-finder-iframe/?', src));
	}
	return false;
};

thx.productCategoryClick = function(category) {

	/*
	@Brief:	Creates the call to the product iframe. Called from child iframe.
	*/
	
	if (category != null) {
		//alert('category = ' + category);
		var src = $.deparam.querystring($('body').find('iframe.product').attr('src'));
		if (category == '0') {
			delete src['category'];
		} else {
			src['category'] = category;
		}
		//alert($.param.querystring('/product-finder-iframe/?', src));
		$('body').find('iframe.product').attr('src', $.param.querystring('/product-finder-iframe/?', src));
	}
	return false;
};

thx.cursorWait = function(element) {
	var ele = $(element);
	ele.css('cursor', 'wait');
};

thx.cursorDefault = function(element) {
	var ele = $(element);
	ele.css('cursor', 'default');
}

thx.certifiedProducts = function() {

	/*
	@Brief:	Certified Products control
	*/

	$("table.list.tablesorter").tablesorter();
};

thx.removeExtranetMenus = function() {
	$('iframe.extranet').contents().find('.topMnuNavBar').addClass('hidden');
};

/* TheSpider, Inc. --- 2010 --- Test Bench Blog */

var site = {
    facebook_share: function (e) {
        url = $(e).attr('share_url');
		title = $(e).attr('share_title');
		clean_title = encodeURIComponent(title);
        clean_url = encodeURIComponent(url);
        window.open('http://www.facebook.com/sharer.php?u=' + clean_url + '&t=' + clean_title + '', '', '');
    }
};

function findAndReplace(searchText, replacement, searchNode) {
    if (!searchText || typeof replacement === 'undefined') {
        alert('nope');
        return;
    }
    var regex = typeof searchText === 'string' ?
                new RegExp(searchText, 'g') : searchText,
        childNodes = (searchNode || document.body).childNodes,
        cnLength = childNodes.length,
        excludes = 'html,head,style,title,link,meta,script,object,iframe';
    while (cnLength--) {
        var currentNode = childNodes[cnLength];
        if (currentNode.nodeType === 1 &&
            (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
            arguments.callee(searchText, replacement, currentNode);
        }
        if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
            continue;
        }
        var parent = currentNode.parentNode,
            frag = (function(){
                var html = currentNode.data.replace(regex, replacement),
                    wrap = document.createElement('div'),
                    frag = document.createDocumentFragment();
                wrap.innerHTML = html;
                while (wrap.firstChild) {
                    frag.appendChild(wrap.firstChild);
                }
                return frag;
            })();
        parent.insertBefore(frag, currentNode);
        parent.removeChild(currentNode);
    }
}

function initAddThis() 
     {
          addthis.init()
     }
     // After the DOM has loaded...	
	
function replaceText(oldString, newString) {
    $("*").each(function() { 
        if($(this).children().length==0) { 
            $(this).text($(this).text().replace(oldString, newString)); 
        } 
    });
}

function cesReplace() {
		$('.wrap h3').html($('.wrap h3').text().replace('Theater', '<span class="ces">CES</span>'));
		$('a.section-cta').html($('a.section-cta').text().replace('Theater', '<span class="ces">CES</span>'));
		$('.latest h3').html($('.latest h3').text().replace('Theater', '<span class="ces">CES</span>'));
}

function initializeFunctions () {
		if($('#thx-c').hasClass('cinetal')) {
			cinetal.initialize();
		}
	}


var cinetal = {
	initialize: function() {
			cinetal.addEventListeners();
		},
		
	addEventListeners: function() {
		$('#cine-tal-form').submit(function() {
			cinetal.validateForm($(this));
			return false;
		});
	},
	
	validateForm: function(form) {
		$('#cine-tal-form .req').each(function() {
			$(this).removeClass('alert')
		});
		
		var message = '';
		var missed = 0;
		var success = true;
		
		$('#cine-tal-form .req').each(function() {
			if ($(this).val() == '') {
				$(this).addClass('alert');
				missed++;
			}
		});
		
		$('#cine-tal-form select').each(function() {
			if ($(this).val() == 0) {
				$(this).addClass('alert');
				missed++;
			}
		});	
		
		if (missed > 0) {
			message += 'Please fill in all required fields!'	
			success = false;
		}
		
		if (success == true) {
			cinetal.sendEmail(form);
			$('#form-message').html('');
		} else {
			$('#form-message').html(message);
		}		
	},
	
	sendEmail: function(form) {
		var $formUrl = $('#form-email-url').val();
		$.post($formUrl, form.serialize(), function (data) {
			
//            var messageJSON = $.parseJSON(d);
//            if (messageJSON.success == "True") {
//                $('#indicator').hide();
//                $('#form-message').removeClass('alarm-message').html('Success! An order confirmation email will be delivered to you shortly.');
//                site.clearForm('ordersupplies-form');
//            } else {
//                $('#indicator').hide();
//                $('#ordersupplies-submit').show();
//                $('#form-message').addClass('alarm-message').html('Failed! Please try again');
//            }
        }, 'json')
	}
}


//EVENTS
$(document).ready(function () {    

	initializeFunctions();	
   
   
	$(".network .i_facebook a").click(function (event) { 
			event.preventDefault();           
			site.facebook_share($(this));
		});
	
	$('#landing .watch_video, #counter-base .watch_video').hover(function() {
			$(this).addClass('on');
		}, function() {
			$(this).removeClass('on');
		});
	
	$('#landing .watch_video, #counter-base .watch_video').click(function() {
		$('.filler').hide();		
	});
		
	thx.inputClear('.tb-search input');
	
	$('.watchvideo_on').hide();
});

