/**
 * @author Electronic Ink
 */

String.prototype.tagPrep = function() {
	marks = "~!@#$%'^&*()_-+={[}]:;\<,>.?/|\\";
	str = this;
	
	for (i = 0; i < marks.length; i++) {
	
		mark = marks.charAt(i);
	
		while (str.indexOf(mark) != -1) {
			point = str.indexOf(mark);
			first_part = str.substring(0, point);
			second_part = str.substring(point + 1, str.length);
			str = first_part + second_part;
		}
	}
	
	//remove multiple sequential space characters
	var stripRegX = /\s{2,}/g;
	str = str.replace(stripRegX,' ');
	
	return str;
}

function disableKUpload(formId)
{
    var action = document.getElementById(formId).action;
    if (action.indexOf('kuploadplus=0') < 0)
    {
        var firstChar = action.indexOf('?') >= 0 ? '&' : '?';
        document.getElementById(formId).action += firstChar + 'kuploadplus=0';
    }
}

jsHover = function() {
            if (document.getElementById("primaryNav") == null)
            {
                return;
            }
            
            var hElms = document.getElementById("primaryNav").getElementsByTagName("LI");

            var lentE=hElms.length;

            for (var i=0; i<lentE; i++) {

                       hElms[i].onmouseover=function() { this.className+=" jshover"; }

                       hElms[i].onmouseout=function() { this.className=this.className.replace(" jshover", ""); }

            }

}

if (window.attachEvent && navigator.userAgent.indexOf("Opera")==-1) window.attachEvent("onload", jsHover);

 


getItemCount = function(list, element)
{
	var listItems = $(list).getElementsByTagName(element);
	var items = $A(listItems);
	
	var count = 0;
	
	items.each(function(items){
			count++;
		});

	return count;
}

toggleLogin = function()
{
	if($('headerLoginForm').style.display == 'none')
	{
		//Display collapse (minus sign) login button
		$('headerLoginLink').style.backgroundPosition = "0px -20px";
	}
	else
	{
		//Display expand (plus sign) login button
		$('headerLoginLink').style.backgroundPosition = "0px 0px";
	}
	Element.toggle($('headerLoginForm'));
}

addLoginPostIdentifier = function()
{
    document.getElementById('loginPost').value = 'loginPost';
}

// Start Blog CMS helper functions
function fillInUrl(nameFieldId, urlFieldId, urlBase, suffix)
{
    var nameField = document.getElementById(nameFieldId);
    var urlField = document.getElementById(urlFieldId);
    
    var id = nameField.value;
    
    urlField.value = urlBase + id.replace(/\ /g, "_") + suffix;
    
    return false;
}

// Start Media Pages scrolling functions
function mediaScrollLeft()
{
	if(moreMediaIndex > 0)
		moreMediaIndex--;
	else
		return;

	var galleryObj = $('moreMediaContent');
	
	new Effect.MoveBy(galleryObj, 0, 56, {queue:'end', duration:.30});
}
function mediaScrollRight()
{
	if(moreMediaIndex < moreMediaCount)
		moreMediaIndex++;
	else
		return;

	var galleryObj = $('moreMediaContent');

	new Effect.MoveBy(galleryObj, 0, -56, {queue:'end', duration:.30});
}

function getCookie(name)
{
    var re = new RegExp(name + "=([^;]*)");
    var result = re.exec(document.cookie);
    
    if (result == null) {
        return '';
    } else {
        return unescape(result[1]);
    }
}

function showPopular(doShow)
{
    if (doShow)
	{
		//D isplay collapse (minus sign) login button
		$('lbPopularLink').style.backgroundPosition = "0px -21px";
		$('lbPopularLink').title = "Popular";
		$('lbPopularContainer').style.display = "block";
	}
	else
	{
		//Display expand (plus sign) login button
		$('lbPopularLink').style.backgroundPosition = "0px 0px";
		$('lbPopularLink').title = "Popular";
		$('lbPopularContainer').style.display = "none";
	}
}

function showTags(doShow)
{
    if (doShow)
	{
		//Display collapse (minus sign) login button
		$('lbViewTagsLink').style.backgroundPosition = "0px -21px";
		$('lbViewTagsLink').title = "Hide tags";
		$('lbTagsContainer').style.display = "block";
	}
	else
	{
		//Display expand (plus sign) login button
		$('lbViewTagsLink').style.backgroundPosition = "0px 0px";
		$('lbViewTagsLink').title = "View tags";
		$('lbTagsContainer').style.display = "none";
	}
}


function togglePopular()
{
    showTags(false);
	showPopular($('lbPopularContainer').style.display == 'none');
}

function toggleTags()
{
    showPopular(false);
	showTags($('lbTagsContainer').style.display == 'none');
}

function toggleMediaTags()
{
	if($('mediaTagsContainer').style.display == 'none')
	{
		//Display collapse (minus sign) login button
		$('mediaTagsLink').style.backgroundPosition = "0px -21px";
		$('mediaTagsContainer').style.display = "block";
	}
	else
	{
		//Display expand (plus sign) login button
		$('mediaTagsLink').style.backgroundPosition = "0px 0px";
		$('mediaTagsContainer').style.display = "none";
	}
}

function showFeatured()
{
	activeList = 'featureListContent';
	swapToggle('topMediaList', 'featureList');
	$('featureToggleLink').style.backgroundPosition = "0px -35px";
	$('topMediaToggleLink').style.backgroundPosition = "0px -0px";
}

function showTopMedia()
{
	activeList = 'mediaListContent';
	swapToggle('featureList', 'topMediaList');
	$('topMediaToggleLink').style.backgroundPosition = "0px -35px";
	$('featureToggleLink').style.backgroundPosition = "0px -0px";
}

function updateScrollCount(list, index, count)
{
	if(activeList == list)
	{
		if(featureIndex < featureCount)
			featureIndex++;
		else
			return;
	}
}
function featureScrollDown()
{
	if(activeList == 'featureListContent')
	{
		if(featureIndex < featureCount)
			featureIndex++;
		else
			return;
	}
	else if(activeList == 'mediaListContent')
	{
		if(topMediaIndex < topMediaCount)
			topMediaIndex++;
		else
			return;
	}
	else if(activeList == 'relatedMediaContent')
	{
		if(relatedMediaIndex < relatedMediaCount)
			relatedMediaIndex++;
		else
			return;
	}
	
	var featureListObj = $(activeList);
	new Effect.MoveBy(activeList, -51, 0, {queue:'end', duration:.30});
}

function featureScrollDown2 (activeList)
{
	if(featureIndex2 < featureCount2)
		featureIndex2++;
	else
		return;
	var featureListObj = $(activeList);
	new Effect.MoveBy(activeList, -51, 0, {queue:'end', duration:.30});
}

function featureScrollUp2(activeList)
{
	if(featureIndex2 > 0)
		featureIndex2--;
	else
		return;
	var featureListObj = $(activeList);
	new Effect.MoveBy(activeList, 51, 0, {queue:'end', duration:.30});		
}

function featureScrollUp()
{
	if(activeList == 'featureListContent')
	{
		if(featureIndex > 0)
			featureIndex--;
		else
			return;
	}
	else if(activeList == 'mediaListContent')
	{
		if(topMediaIndex > 0)
			topMediaIndex--;
		else
			return;
	}
	else if(activeList == 'relatedMediaContent')
	{
		if(relatedMediaIndex > 0)
			relatedMediaIndex--;
		else
			return;
	}

	var featureListObj = $(activeList);

	new Effect.MoveBy(activeList, 51, 0, {queue:'end', duration:.30});		
}




// Start Media Pages scrolling functions
function mediaScrollLeft()
{
	if(moreMediaIndex > 0)
		moreMediaIndex--;
	else
		return;

	var galleryObj = $('moreMediaContent');
	
	new Effect.MoveBy(galleryObj, 0, 56, {queue:'end', duration:.30});
}

function mediaScrollRight()
{
	if(moreMediaIndex < moreMediaCount)
		moreMediaIndex++;
	else
		return;

	var galleryObj = $('moreMediaContent');

	new Effect.MoveBy(galleryObj, 0, -56, {queue:'end', duration:.30});
}

// End Media Page scroll functions

// verification page function
function confirmAge() {
    var location = window.location + '';
    var url = unescape(location.substring(location.indexOf("returnUrl=") + 10, 1024));
    
    document.cookie = "has_been_verified=true;";
    window.location = url;
    return false;
}

// XMLHttpRequest handler class for home page and landing page featured items

function XHR_handler(returnFormat, url, dataMethod, popFunction)
{
	//Tracks active calls and prevents calls from overlapping
	this.callActive = false;
	this.targetURL = url;
	this.AjaxUpdate = function(params, targetEl, toggleButton)
	{
		if(returnFormat == 'String')
		{
			$(targetEl).innerHTML = '<img src="images/loading.gif" id="ajaxIndicator" alt="" />';
			var myAjax = new Ajax.Request(
				this.targetURL,
				{method:dataMethod,	parameters:params, onComplete:popFunction}
			);
		}
		else if(returnFormat == 'XML')
		{
			var myAjax = new Ajax.Request(
				this.targetURL,
				{method:dataMethod,	parameters:params, onComplete:popFunction}
			);
		}
	}
}

moveToggle = function(toggleButton)
{
	if($(toggleButton).className != 'selectedCategory')
	{
		$(toggleButton).className = 'selectedCategory';
		return true;
	}
	else
	{
		$(toggleButton).className = '';
		return false;
	}
}

showFeature = function(orRequest)
{
	$('currentFeature').innerHTML = orRequest.responseText;
}

showComments = function(orRequest)
{
	$('commentsContent').innerHTML = orRequest.responseText;
}

function toggleTooltip(clickEvent, imgObj)
{
	// get the tooltip Div element
	var sourceEl = (imgObj.getElementsByTagName('div'))[0];
	var targetEl = $('tooltipTarget'); 
	targetEl.innerHTML = sourceEl.innerHTML+'<img src="/images/tooltip_spike.gif" height="10" width="10" alt="" style="position:absolute;bottom:-10px;left:0px;" />';
	// toggle the display
	if(clickEvent.type == 'mouseover')
	{
		Event.observe(
			document,
			'mousemove',
			function(evt)
			{
				moveTooltip(evt, targetEl);
			}
		);
		//Effect.toggle(targetEl.id, 'appear', {queue:'end'});
		targetEl.style.display = '';
	}
	else if(clickEvent.type == 'mouseout')
	{
		Event.stopObserving(
			document,
			'mousemove',
			function(evt)
			{
				moveTooltip(evt, targetEl);
			}
		);
		//Effect.toggle(targetEl.id, 'appear', {queue:'end'});
		targetEl.style.display = 'none';
	}
	moveTooltip(clickEvent, targetEl);
}

function moveTooltip(evt, targetEl)
{
	var topPos = evt.clientY-15-targetEl.offsetHeight;
	var leftPos = evt.clientX;
	if(navigator.appVersion.indexOf('Safari') == -1)
	{
		if(window.pageYOffset)
		{
			topPos += window.pageYOffset;
			leftPos += window.pageXOffset;
		}
		else
		{
			topPos += (document.compatMode && document.compatMode != "BackCompat")? document.documentElement.scrollTop : document.body.scrollTop;
			leftPos += (document.compatMode && document.compatMode != "BackCompat")? document.documentElement.scrollLeft : document.body.scrollLeft;
		}
	}
	targetEl.style.top = String(topPos)+'px';
	targetEl.style.left = String(leftPos)+'px';
}

// Start of CMS Functions

// SwapTags
// This functions append the new option object to the end of the listbox
function swapTags(fromCellId, toCellId)
{
	// get fromListBox object and selected option value
	var fromListBox = $(fromCellId).getElementsByTagName('select')[0];

	if(fromListBox.selectedIndex > -1)
	{		
		var selectedTag = fromListBox.options[fromListBox.selectedIndex].value;
		
		// get toListBox object
		var toListBox = $(toCellId).getElementsByTagName('select')[0];
		
		// create a new Option element and add to the toListBox object -  Option( text,  value)
		var newTagOption = new Option(selectedTag, selectedTag);
		toListBox.options.add(newTagOption);
		
		// remove selected option from the tags list box
		fromListBox.remove(fromListBox.selectedIndex);
	}
}


// ConfirmDelete
// This functions prompts the user to confirm that they want to delete the current content
function confirmDelete(contentName)
{
	return window.confirm('Are you sure you want to delete ' + contentName + '?');
}

function confirmMassDelete()
{
    return window.confirm('Are you sure you want to delete all items you are editing now?');
}

function confirmGridDelete(amount)
{
    if (amount != 0)
    {
        if (amount != 1)
        {
            return window.confirm('Are you sure you want to delete all ' + amount + ' selected items?');
        }
        else
        {
            return window.confirm('Are you sure you want to delete the selected item?');
        }
    }
    else
    {
        window.alert('Please, select at least one item to delete.');
        return false;
    }
}

checkSelectedAmount = function(allowMultipleSelection)
{
    if (jsSelectedAmount == 0)
    {
        window.alert('Please, select at least one item!');
        return false;
    }
    if ((allowMultipleSelection == 0) && (jsSelectedAmount > 1))
    {
        window.alert('Grid does not support multiple items editing. Please select single item to proceed.');
        return false;
    }
    return true;
}

setGlobalCheckStatus = function(globalCheckBox)
{
    for (var index = 0; index < checkBoxes.length; index++) 
    {
        var checkBox = document.getElementById(checkBoxes[index]);
        if (checkBox.checked != globalCheckBox.checked)
        {
            if (globalCheckBox.checked)
            {
                jsSelectedAmount++;
            }
            else
            {
                jsSelectedAmount--;
            }
            checkBox.checked = !checkBox.checked;
        }
    }
}

changeCheckBoxValue = function(checkBox)
{
    if (checkBox.checked)
    {
        jsSelectedAmount++;
        jsAllSelected = true;
        for (var index = 0; index < checkBoxes.length; index++) 
        {
            var checkBox = document.getElementById(checkBoxes[index]);
            if (!checkBox.checked)
            {
                jsAllSelected = false;
                break;
            }
        }
    }
    else
    {
        jsSelectedAmount--;
        if (jsAllSelected)
        {
            jsAllSelected = false;
        }
    }
    document.getElementById(jsGlobalCheckBoxId).checked = jsAllSelected;
}

checkSelectedCount = function(checkBoxes)
{
    var selectedCount = countCheckBoxCheckedValue(checkBoxes);
    if (selectedCount == 0)
    {
        window.alert('Please, select at least one item!');
        return false;
    }
    else
    {
        return true;
    }
}

countCheckBoxCheckedValue = function(checkBoxes)
{
    var jsSelectedCount = 0;
    if (checkBoxes)
    {
        for (var index = 0; index < checkBoxes.length; index++) 
        {
            var checkBox = document.getElementById(checkBoxes[index]);
            if (checkBox.checked)
            {
                jsSelectedCount++;
            }
        }
    }
    return jsSelectedCount;
}
changeCheckBoxesValue = function(checkBoxes,value)
{
    if (checkBoxes)
    {
        for (var index = 0; index < checkBoxes.length; index++) 
        {
            var checkBox = document.getElementById(checkBoxes[index]);
            if (checkBox.checked)
            {
                checkBox.checked = value;
            }
        }
    }
    
    return false;
}

confirmDeleteSelected = function(checkBoxes,contentName)
{
    if (checkSelectedCount(checkBoxes))
    {
        if(confirmDelete(contentName))
            return true;
    }
    return false;
}



// Check Selection of Layout Dropdowns
// This function makes sure that the user doesn't select the  dividing line ('---------------') which is only used
// as a divider. This is only needed for IE users.
function checkSelection(dropdownObj)
{
	if(dropdownObj.selectedIndex == 1)
	{
		$('pageError').innerHTML = "The selected dropdown option is invalid. Please try again.";
	}
	else
	{
		if($('pageError').innerHTML != "")
			$('pageError').innerHTML = "";
	}
}

function ClearRegistrationErrorMessage()
{
    $('ErrorMessage').innerHTML = '';
}

// Archive control

blogArchivePrevYear = function()
{
    var yearElement = $('blogArchiveYear');
    var minYear = parseInt(yearElement.getAttribute('minYear'));
    var year = parseInt(yearElement.innerHTML);
    var newYear;
    
    if (year && year > minYear)
    {
        newYear = year - 1;
    }
    else
    {
        newYear = minYear; 
    }
    yearElement.innerHTML = newYear;
    
    rebuildLinks(year, newYear);
}

blogArchiveNextYear = function()
{
    var yearElement = $('blogArchiveYear');
    var maxYear = parseInt(yearElement.getAttribute('maxYear'));
    var year = parseInt(yearElement.innerHTML);
    var newYear;
    
    if (year && year < maxYear)
    {
        newYear = year + 1;
    }
    else
    {
        newYear = maxYear; 
    }
    yearElement.innerHTML = newYear;
    
    rebuildLinks(year, newYear);
}

rebuildLinks = function(oldYear, newYear)
{
    var linksElement = $('blogContainerArchive');
    var links = linksElement.getElementsByTagName('a');

    for (var i = 0; i < links.length; i++)
    {
        var link = links[i];
        var href = link.getAttribute('href');
        href = stringReplace(href, oldYear, newYear);
        link.setAttribute('href', href);
    } 
}

stringReplace = function(href, oldString, newString)
{
    var position = href.indexOf(oldString);
    if (position > -1)
    {
        var startString = href.substr(0, position);
        var endString = href.substring(position + oldString.toString().length, href.length);
        
        return startString + newString + endString;
    }
    
    return href;
}
var messageBox = function(element)
{
    return confirm('Are you sure, you want to delete ' + element + '?');
}

function redirectIphone(){
		var reg = new RegExp(".*Mobile\/.+Safari.*");
		var userAgent = navigator.userAgent;
	
		if(reg.test(userAgent))
		{
			window.location.href = "http://www.liquidgeneration.com/iphone/index.html";
		}
}

function openNewWindow(url, title) {
    var newWindow = window.open(url, 'title', 'width=860,height=595,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=yes,screenX=300,screenY=200,left=200,top=200');
    //newWindow.show(300, 200, 860, 595);
    return false;
}
