/*

BASE Functions

==================================================================================================================*/	

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

/* This function returns the number of tags or products/services remaining */
function getRemaining(parent){
	switch(parent){
		case '#products_services': 
			return (productlimit - getCurrentList(parent).length);
		break;
		case '#categories':
			return (catlimit - getCurrentList(parent).length);
		break;
		case '#Tags':
			return (taglimit - getCurrentList(parent).length);
		break;
	}
	return 0;		
}

/* Refresh the tables for supplier products / listings */
function refreshTables(){
	$('#categories, #products_services, #Tags').each(function(){
		var id = '#' + $(this).attr('id');
		var list = getCurrentList(id);
		$.each(list,function(index, value){
			if (id == '#products_services') {
				var tempList = value.split('|');
				$('#products_services table tbody').append("<tr><th scope=\"row\">" + tempList[0] + "</th><td>" + tempList[1] + "</td><td><a class=\"remove\" href=\"#\">Remove</a></td></tr>");
			}
			else{
				$(id + ' table tbody').append("<tr><th scope=\"row\">" + value + "</th><td><a class=\"remove\" href=\"#\">Remove</a></td></tr>");					
			}
			
		});
		updateTotal(id);
	});
}

function getCurrentList(parent){
	var list = new Array();
	if ($(parent).find('.list input:hidden').val().length > 0) {
		list = $(parent).find('.list input:hidden').val().split(';');
	}
	return list;
}

function addItem(parent, item){
	var list = getCurrentList(parent);
	list.push(item);				
	$(parent).find('input:hidden').val(list.join(';'));
	updateTotal(parent);
}

function removeItem(parent, index){
	var list = getCurrentList(parent);
	if (list.length == 1 && index == 1)
	{
		index = 0;
	}
	list.splice(index,1);
	$(parent).find('input:hidden').val(list.join(';'));
	updateTotal(parent);
}
function updateTotal(parent){
	$(parent).find('.add').removeClass('enabled disabled');
	$(parent).find('.upgradeInfo').removeClass('enabled');
	if(getRemaining(parent) > 0)
	{
		$(parent).find('.add').addClass('enabled');
		$(parent).find('.additions').slideToggle();			
	}
	else
	{
		switch(parent){
			case '#products_services': 
				$(parent).find('.upgradeInfo').addClass('enabled');
			break;
			case '#categories':
				$(parent).parent().parent().parent().find('.upgradeInfo').addClass('enabled');
			break;
			case '#Tags':
				$(parent).parent().parent().parent().find('.upgradeInfo').addClass('enabled');
			break;
		}
		
		$(parent).find('.add').addClass('disabled');
		$(parent).find('.additions').css('display','none');
		
	}		
}

function DeletePressRelease(nodeId) {

    // Confirm before delete
    if (confirm('Are you sure you want to delete the press release?  You cannot undo this action!')) {

        // Delete press release
        $.post("/supplier-press-releases/press-release-manager---ajax.aspx", { action: "delete", id: nodeId }, function() {

            // Show submitted message
            $('.info').show().text("Successfully deleted press release").fadeOut(1500);

            // Remove li
            $("#submit_" + nodeId).closest('.supplier-pr-working').remove();
        });
    }
}

function SubmitPressRelease(nodeId, link) {

    // Submit press release
    $.post("/supplier-press-releases/press-release-manager---ajax.aspx", { action: "submit", id: nodeId }, function() {

        // Show submitted message
        $('.info').show().text("Your press release has been submitted for approval!").fadeOut(1500);

        // Toggle class on li
        $("#submit_" + nodeId).closest('.supplier-pr-working').removeClass('supplier-pr-working').addClass('supplier-pr-submitted');

        // Replace edit/delete/submit links with unsubmit link
        $("#submit_" + nodeId).closest('.actions').html("<span id=\"unsubmit_" + nodeId + "\" class=\"unsubmit\"><a href=\"#\" onclick=\"UnsubmitPressRelease(" + nodeId + ", '" + link + "'); return false;\">Unsubmit</a></span>");
    });
}

function UnsubmitPressRelease(nodeId, link) {

    // Unsubmit press release
    $.post("/supplier-press-releases/press-release-manager---ajax.aspx", { action: "unsubmit", id: nodeId }, function() {

        // Show submitted message
        $('.info').show().text("Your press release has been unsubmitted.").fadeOut(1500);

        // Toggle class on li
        $("#unsubmit_" + nodeId).closest('.supplier-pr-submitted').removeClass('supplier-pr-submitted').addClass('supplier-pr-working');

        // Replace unsubmit link with edit/delete/submit links
        $("#unsubmit_" + nodeId).closest('.actions').html("<span class=\"edit\"><a href=\"" + link + "\">Edit</a></span>\n<span class=\"delete\"><a href=\"#\" onclick=\" DeletePressRelease('" + nodeId + "', '" + link + "'); return false;\">Delete</a></span>\n<span id=\"submit_" + nodeId + "\" class=\"submit\"><a href=\"#\" onclick=\" SubmitPressRelease('" + nodeId + "', '" + link + "'); return false;\">Submit</a></span>");
    });
}

function SaveNewPressRelease() {
    var headline = $('.headline').val();
    var content = $('.mceFirst').children().children().contents().find('#tinymce').html().replace('<br _mce_bogus=\"1\">', '').replace(/["]/g, '&quot;');
    var nodeId = getURLParameter("id");

    // Save press release
    $.post("/supplier-press-releases/press-release-manager---ajax.aspx", { action: "previewSave", id: nodeId, headline: headline, content: content }, function() {
        document.location.href = "/supplier-press-releases/press-release-manager.aspx";
    });
}

function SubmitNewPressRelease() {
    var headline = $('.headline').val();
    var content = $('.mceFirst').children().children().contents().find('#tinymce').html().replace('<br _mce_bogus=\"1\">', '').replace(/["]/g, '&quot;');
    var nodeId = getURLParameter("id");

    // (Save and) Submit press release
    $.post("/supplier-press-releases/press-release-manager---ajax.aspx", { action: "previewSubmit", id: nodeId, headline: headline, content: content }, function() {
        document.location.href = "/supplier-press-releases/press-release-manager.aspx";
    });
}

function CloseShadowBoxAndRedirect() {
    Shadowbox.close();
    document.location.href = "/supplier-press-releases/press-release-manager.aspx";
}

function getURLParameter(name) {
    return unescape(
                    (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, 0])[1]
                );
}


function isApple() {
	var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if (agentID) {
		return true;	
	}
	else{
		return false;	
	}
}

function isDroid() {
	var ua = navigator.userAgent.toLowerCase();
	var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
	if(isAndroid) {
		return true;	
	}
	else{
		return false;	
	}
}


//jQuery Load
$(document).ready(function() {

	//Mobile and Tablet Navigation override (dropdowns on hover turn to click)
	var apple = isApple();
	var android = isDroid();
	if (apple || android){
		$('#main-nav').addClass("mobile");
		$('#main-nav').find('.drop').find('a:first').removeAttr("href").addClass("parent");
		$('#navigation .mobile li.drop').click(function() {
			$(this).find('ul').toggle('slow');
		});
	}


    //Top20 Main Page Tooltip for Archive Years
	$('.lists .archive-link').click(function(){
		if ( $(this).parent().hasClass('active') ) {
			$(this).parent().removeClass('active');			 
		} else {
			$('.more-links').parent().removeClass('active');
			$(this).parent().addClass('active');
		}
		return false;
	 });
	 $('.more-links .close').click(function(){
		if ( $(this).parent().parent().hasClass('active') ) {
			$(this).parent().parent().removeClass('active');			 
		} return false; 
	 });
	 
	
	
	//Supp. Directory Feature Comp Slider
	$('.sd-featured-suppliers .scroller ul').bxSlider({
		displaySlideQty: 6,
		moveSlideQty: 6
	});




	/* Supplier Directory Sort Form */
	$('#sortSuppBy').bind("change",function(){	
		var urlVars = getUrlVars();
		if (urlVars["tag"] != null) {
			window.location.href = "?tag=" + urlVars["tag"] + "&order=" + $('#sortSuppBy').val();
		}
		else {
			window.location.href = "?order=" + $('#sortSuppBy').val();
		} 
	});
	$('#ddlCommunity').change(function(){
		window.location.href = "/learning-communities/" + $('#ddlCommunity').val() + "?order=" + $('#sortSuppBy').val(); 
	});	


	/* Supplier Registration live preview */
			// Company Name locator
			$(".reg-form .title_li input").keyup(function(){
				thisvalue = $(this).attr("value");
				$("#your-supplier-link .fn").html(thisvalue);
			});
			// URL
			$(".reg-form .companyURL_li input").keyup(function(){
				thisvalue = $(this).attr("value");
				$("#your-supplier-link p.website a").html(thisvalue);
				$("#your-supplier-link p.website a").attr("href", "http://" + thisvalue);
				$("#your-supplier-link li.website a").html(thisvalue);
				$("#your-supplier-link li.website a").attr("href", "http://" + thisvalue);
			});
			// Phone
			$(".reg-form .companyPhone_li input").keyup(function(){
				thisvalue = $(this).attr("value");
				$("#your-supplier-link li.tel").html(thisvalue);
			});
			// Description
			$(".reg-form .description_li textarea").keyup(function(){
				thisvalue = $(this).attr("value");
				$("#your-supplier-link div.summary p").html(thisvalue);
			});
			
			
	/* Supplier Registration Add/Remove Items, etc. */
	var remaining = 0;
        $('.save a').click(function(){
						var parent = '#' + $(this).parents("fieldset").attr('id');
						var patt = /^[A-Za-z -]+$/;
						if(getRemaining(parent) > 0){
							if(parent == '#products_services'){
								$('#products_services table tbody').append("<tr><th scope=\"row\">"+$('#products_services #itemName').val()+"</th><td>"+$('#products_services #itemURL').val()+"</td><td><a class=\"remove\" href=\"#\">Remove</a></td></tr>");
								addItem(parent, $('#products_services #itemName').val()+'|'+$('#products_services #itemURL').val());
								$('#products_services #itemName').val('');
								$('#products_services #itemURL').val('');				
							}
							else if(parent == '#Tags' && !patt.test($('#tag').val())){
								alert('Please only use letters and spaces.');
								return false;
							}
							else{
								$(parent + ' table tbody').append("<tr><th scope=\"row\">" + $(parent + ' .dynamicinput').val() + "</th><td><a class=\"remove\" href=\"#\">Remove</a></td></tr>");
								addItem(parent, $(parent + ' .dynamicinput').val())
								$(parent + ' .dynamicinput').val('');
							}
					        		
						}
						return false;	
        });	

        		
				
		$('.remove').live("click",function(){			
			//updateTotal('#' + $(this).parents("fieldset").attr('id'));
			removeItem('#' + $(this).parents("fieldset").attr('id'), $(this).parents('tr').index());
			$(this).parents('tr').remove();						
			return false;
		});
		
		
		
		$('#detailed_summary .headline').change(function(){
			$('.summary p').text($('#detailed_summary .headline').val());
		});
		
		refreshTables();
    
		/* tags/categories/products listing */
		$('div.add a').live('click',function(){
			var parent = '#' + $(this).parents("fieldset").attr('id');
			if (getRemaining(parent) > 0) {
				$(this).parent().parent().children('.available').addClass('enabled');
				$(this).parent().parent().children('.available').children('.additions').slideToggle();
				$(this).parent().removeClass('enabled');
			}
		});

		/* TII Article First Letter Cap */
		$(".article-main .user p:eq(0)").each(function(){
			  var paragraph = jQuery.trim($(this).html());
			  var firstLetter = paragraph.substring(0,1);
			  var restOfParagraph = paragraph.substring(1);
			  newParagraph = '<p><span class="drop-cap">' + firstLetter + '</span>' + restOfParagraph + '</p>';
			  $(this).replaceWith( newParagraph );
		});

		
		/* Blog */
		$('.archive-hidden').hide();
		
		$('.archive-view-more').live("click",function(){
			$('.archive-hidden').slideToggle();
		});
		
		$('.blog-post-content p:empty').remove();
		$("#blog-listing .blog-post-content p:first-child").each(function(){
			var paragraph = jQuery.trim($(this).text());
			var firstLetter = paragraph.substring(0,1);
			var restOfParagraph = paragraph.substring(1);
			newParagraph = '<p><span class="drop-cap">' + firstLetter + '</span>' + restOfParagraph + '</p>';
			$(this).replaceWith( newParagraph );
		});
		
		$("#blog-post .blog-post-content p:eq(0)").each(function(){
			var paragraph = jQuery.trim($(this).text());
			var firstLetter = paragraph.substring(0,1);
			var restOfParagraph = paragraph.substring(1);
			newParagraph = '<p><span class="drop-cap">' + firstLetter + '</span>' + restOfParagraph + '</p>';
			$(this).replaceWith( newParagraph );
		});
		/* End Blog */ 

},function(){
	//GUnload();
});


// Print Page
function printThis() {
	(window.print) ? window.print() : alert('To print his page press Ctrl-P on your keyboard \nor choose print from your browser or device after clicking OK');
}
