// for the google custom serach engine search box
function convert(mySel) {
	// first i check to see if they've entered something besides
	// Search Our Site - this prevents people from submitting the
	// default value as a search term
	if (mySel.value == "Search Our Site") {
		return false;
	} else {
		// declaring variables
		var myWin, myVal, gcseCode;
		// Google gives each of its custom search engines an id, so
		// we need to set the variable that holds this value based on
		// which domain we're on
		if (location.host.indexOf("www.cosmeticsandtoiletries.com") >= 0) {
			gcseCode = "xza5h_cqlz8";
		} else if (location.host.indexOf("www.gcimagazine.com") >= 0) {
			gcseCode = "orvhyiscjqi";
		} else if (location.host.indexOf("www.mergeonline.com") >= 0) {
			gcseCode = "lw94lybeezm";
		} else if (location.host.indexOf("www.perfumerflavorist.com") >= 0) {
			gcseCode = "0xaqj4wjnme";
		} else if (location.host.indexOf("www.skininc.com") >= 0) {
			gcseCode = "qhcvuq8a7qo";
		}
		// set the search terms to a variable
		myVal = mySel.value;
		// do some replacing to make sure the url looks ok
		myVal = myVal.replace(/ /g,"+");
		myVal = myVal.replace(/"/g,"%22");
		myVal = myVal.replace(/&/g,"%26");
		// now we add the url we'll be directing them to with the
		// search terms
		myVal = "http://" + location.host + "/search?cx=012659430018965267705%3A" + gcseCode + "&cof=FORID%3A11&q=" + myVal;
		// this next part i don't really understand, but clearly
		// we're using myVal to set myWin and then going there
		if (myVal) {
			if (mySel.form.target) {
				myWin = parent[mySel.form.target];
			} else {
				myWin = window;
			}
			if (!myWin) { return true; }
			myWin.location = myVal;
		}
		return false;
	}
}

// expand-collapse stuff
function toggleDiv(){
	var hiddenDiv = document.getElementById('collapse');
	var toggleLink = document.getElementById('toggleLink');
	
	if (hiddenDiv.style.display == "none") {
		hiddenDiv.style.display = "block";
		toggleLink.style.backgroundImage="url(http://media.allured.com/designimages/collapse_icon.gif)";
		toggleLink.innerHTML = "collapse";
	}
	else {
		hiddenDiv.style.display = "none";
		toggleLink.style.backgroundImage="url(http://media.allured.com/designimages/expand_icon.gif)";
		toggleLink.innerHTML = "expand";
	}
}

function closeDevDiv() {
	document.getElementById('devHeader').style.display = "none";
}

// for the search form on the directory solution
function refineSearch(){
	document.getElementById('searchForms').style.display = "block";
	// this is the p tag
	var refineSearchPara = document.getElementById('refineSearch');
	// this is the a tag
	var refineSearchLink = document.getElementById('refineSearchLink');
	// this is the text "Refine Your Search"
	var refineLinkString = refineSearchLink.innerHTML;
	refineSearchPara.removeChild(refineSearchLink);
	refineSearchPara.innerHTML = "<span>" + refineLinkString + "</span>";
}

function zebraStripe() {
	var allTables, thisTable, allRows, thisRow;
	allTables = document.getElementsByTagName('table');
	for (var j = 0; j < allTables.length; j++) {
		thisTable = allTables[j];
		if (thisTable.className == 'tablesorter' || thisTable.className == 'phase' ) {
			//alert("found one");
			//thisTable.setAttribute("cellspacing", "10");
			//thisTable.setAttribute("border", "0");
			//thisTable.setAttribute("cellpadding", "20");
			//thisTable.setAttribute("width", "400");
			allRows = thisTable.getElementsByTagName('tr');
			for (var i = 0; i < allRows.length; i++) {
				thisRow = allRows[i];
				if (i % 2 === 0) {
					thisRow.className = 'even';
				} else {
					thisRow.className = 'odd';
				}
			}
		} 
	}	
}

window.onload = zebraStripe;

function twitterFeedCheck() {
	if ($('#twitter_update_list li').length > 0) {
		$('#twitter_div').show();
	}
}

function toggleFields(fields) {
	var toggleFieldIDs = fields.split(",");
	for (var i = 0; i < toggleFieldIDs.length; i++) {
		var toggleFieldID = toggleFieldIDs[i];
		var toggleField = document.getElementById(toggleFieldID);
		var hasLabel = false;
		var toggleFieldLabel;
		if (toggleField.previousSibling.previousSibling.nodeName == "LABEL") {
			hasLabel = true;
			toggleFieldLabel = toggleField.previousSibling.previousSibling;
		}
		if (toggleField.disabled === false) {
			toggleField.disabled = true;
			if (hasLabel) {
				if (toggleFieldLabel.className != "") {
					toggleFieldLabel.className = toggleFieldLabel.className + " disabled";
				} else {
					toggleFieldLabel.className = "disabled";
				}
			}
		} else if (toggleField.disabled === true) {
			toggleField.disabled = false;
			if (hasLabel) {
				if (toggleFieldLabel.className == "disabled") {
					toggleFieldLabel.className = "";
				} else {
					toggleFieldLabel.className = toggleFieldLabel.className.replace(/ disabled/, "");
				}
			}
		}
	}
}

function createGalleryAds(galleryAds) {
	// while this is a loop, it really should only ever get executed once - there is probably a better way to write this, but i don't know it yet
	for (var i = 0; i < galleryAds.length; i++) {
		// setup the ad variable
		var ad = galleryAds[i].photo_gallery_ad;
		// if we're on the actual photo gallery, then we produce the ad, otherwise, we're on the report and just need to add the sponsor message
		if (gallery) {
			// we get the adColumn to insert our div at the end of it
			var adColumn = document.getElementById('col2');
			// we get the iframe so that we can change its height property at the end of the function
			var iframe = document.getElementById('galleryThumbs');
			// by default we're going to do an ad with both the headline and copy, but if they aren't present, then we do a logo only ad
			var logoOnly = false;
			if (ad.ad_copy == '' || ad.ad_headline == '') {
				logoOnly = true;
			}
			// create the overall div and then give it the proper class based on which format we're doing
			var adDiv = document.createElement('div');
			adDiv.id = 'sponsor';
			if (logoOnly) {
				adDiv.className = 'center';
			} else {
				adDiv.className = 'left';
			}
			// create the h4 and add it to the sponsor div
			var sponsorSlug = document.createElement('h4');
			var sponsorSlugText = document.createTextNode('Sponsored by:');
			sponsorSlug.appendChild(sponsorSlugText);
			adDiv.appendChild(sponsorSlug);
			// create the linked logo and attach it to the sponsor div
			var adLink = document.createElement('a');
			adLink.href = adServerURL + '/click/gallery_ad/' + ad.id + '/?q=' + query + '&s=' + skip;
			adLink.target = '_parent';
			var logo = document.createElement('img');
			logo.src = adServerURL + ad.logo_path;
			adLink.appendChild(logo);
			adDiv.appendChild(adLink);
			// for the format with text, we have to do a couple other things
			if (!logoOnly) {
				// create the h2 and get its text from the ad, then attach to the sponsor div
				var adHeadline = document.createElement('h2');
				var adHeadlineText = document.createTextNode(ad.ad_headline);
				adHeadline.appendChild(adHeadlineText);
				adDiv.appendChild(adHeadline);
				// create the p and get its text from the ad, then attach to the sponsor div
				var adCopy = document.createElement('p');
				var adCopyLink = document.createElement('a');
				adCopyLink.href = adServerURL + '/click/gallery_ad/' + ad.id + '/?q=' + query + '&s=' + skip;
				adCopyLink.target = '_parent';
				var adCopyText = document.createTextNode(ad.ad_copy);
				adCopyLink.appendChild(adCopyText);
				adCopy.appendChild(adCopyLink);
				adDiv.appendChild(adCopy);
			}
			// finally, we just add the sponsor div to the adColumn
			adColumn.appendChild(adDiv);
			// only adjust the height of the iframe if we have an ad
			iframe.height = '415';
		} else {
			// for this case, we're just going to create a p tag with the sponsor to give them recognition
			// the first thing we do is locate both the div and ul that we'll need in order to insert the p in the right place
			var galleryDiv = document.getElementById('gallery');
			var galleryList = document.getElementById('galleryList');
			// then we create the p and add its text node
			var sponsorPara = document.createElement('p');
			sponsorPara.id = 'gallerySponsor';
			var sponsorParaText = document.createTextNode('Sponsored By: ' + ad.advertiser.company_name);
			sponsorPara.appendChild(sponsorParaText);
			// now we just insert the p
			galleryDiv.insertBefore(sponsorPara, galleryList);
		}
	}
}

function createAuthorBio(bios) {
	// the idea here is to get the col2_content div and the related div and use insertBefore() to tuck the authorBio div in the DOM right before the related div
	var contentColumn = document.getElementById('col2_content');
	var relatedDiv = document.getElementById('related');
	for (var i = 0; i < bios.length; i++) {
		var bio = bios[i].author_bio_ad;
		var authorBioDiv = document.createElement('div');
		authorBioDiv.id = 'authorBio';
		// create the product div
		var productDiv = document.createElement('div');
		productDiv.id = 'product';
		// create the link and add the image to it
		var productLink = document.createElement('a');
		productLink.href = adServerURL + '/click/author_bio/' + bio.id + '/?q=' + query.replace(/\s/g, '+') + '&s=' + skip;
		var productImage = document.createElement('img');
		productImage.src = adServerURL + bio.product_path;
		productImage.alt = bio.product_title;
		productLink.appendChild(productImage);
		// create the p and add the text to it
		var productCaption = document.createElement('p');
		var productCaptionText = document.createTextNode(bio.product_title);
		productCaption.appendChild(productCaptionText);
		// add the link and the caption to the product div
		productDiv.appendChild(productLink);
		productDiv.appendChild(productCaption);
		// create the headshot div
		var headshotDiv = document.createElement('div');
		headshotDiv.id = 'headshot';
		// create the image tag
		var headshotImage = document.createElement('img');
		headshotImage.src = adServerURL + bio.headshot_path;
		// create the p and add the text to it
		var headshotCaption = document.createElement('p');
		var headshotCaptionText = document.createTextNode(bio.author_name);
		headshotCaption.appendChild(headshotCaptionText);
		// add the image and caption to the headshot div
		headshotDiv.appendChild(headshotImage);
		headshotDiv.appendChild(headshotCaption);
		// create the bio div
		var bioDiv = document.createElement('div');
		bioDiv.id = 'bio';
		// create the h4 label
		var label = document.createElement('h4');
		var labelText = document.createTextNode('About the Author:');
		label.appendChild(labelText);
		// create the h2 with the authors name
		var authorName = document.createElement('h2');
		var authorNameText = document.createTextNode(bio.author_name);
		authorName.appendChild(authorNameText);
		// create the p tag with the text of the author's bio
		var authorBio = document.createElement('p');
		var authorBioText = document.createTextNode(bio.author_bio);
		authorBio.appendChild(authorBioText);
		// create the p tag for the product suggestion
		var productMessage = document.createElement('p');
		var productMessageText = document.createTextNode('Suggested further reading: ');
		var productMessageLink = document.createElement('a');
		productMessageLink.href = adServerURL + '/click/author_bio/' + bio.id + '/?q=' + query.replace(/\s/g, '+') + '&s=' + skip;
		var productMessageLinkText = document.createTextNode(bio.product_title);
		productMessageLink.appendChild(productMessageLinkText);
		productMessage.appendChild(productMessageText);
		productMessage.appendChild(productMessageLink);
		// add the label, author name and author bio elements to the bio div
		bioDiv.appendChild(label);
		bioDiv.appendChild(authorName);
		bioDiv.appendChild(authorBio);
		bioDiv.appendChild(productMessage);
		//
		authorBioDiv.appendChild(productDiv);
		authorBioDiv.appendChild(headshotDiv);
		authorBioDiv.appendChild(bioDiv);
		//
		contentColumn.insertBefore(authorBioDiv, relatedDiv);
	}
}

$(document).ready(function() {
	// adds a click handler for trackMe links - this should only work on Sponsored Content
	$('a.trackMe').click(function() {
		// we can only do this if pageTracker has been set and we don't want dev tracked (or adtest)
		if (pageTracker && location.host.indexOf('dev') < 0 && location.href.indexOf('adtest') < 0) {
			// check to see if we're on the classified page
			if ($('body').attr('id') == 'Magazine-ClassifiedAds') {
				// this is in the format of 'category', 'action', 'label'
				pageTracker._trackEvent('Classified Ads', $(this).attr('href'));
			// all other pages (sponsored content)
			} else {
				// for the action, i use the id attribute, which is easy to set except for the case of the links in the actual copy of the item, so this takes care of them
				var eventAction = $(this).attr('id');
				if (eventAction == '') {
					eventAction = 'sponsoredText';
				}
				// this is in the format of 'category', 'action', 'label'
				pageTracker._trackEvent('Sponsored Content', eventAction, location.pathname.split('/')[location.pathname.split('/').length - 1].split('.')[0]);
			}
		}
	});
});
