// Ellen-Wille Javascript 
// jquery 1.2.6

$(function(){
	// Sprachauswahl box
	$('#languageSelect').bind('change', function( e ) {
		if( $('#languageSelect').val() != '' ) {
			document.location.href = $('#languageSelect').val();
		}
	});

	// Image Zoom auf Produktseite
	if( $('#imageZoom').length ) {
		prepareImageZoom();
	}
	
	// Suchfunktion
	if( $('#searchForm').length ) {
		prepareSearchForm();
	}
	
	// IE Form Label fix für Katalogbestellung
	if( $.browser.msie ) { 
		$('label.catalogImage').bind('click', function() {
			$('#' + $(this).attr('for') ).click();
		});
	}
	
	// Mouseover Farbzoom
	if( $('div.productColor').length ) {
		prepareProductColorZoom();
	}
	
	if( $('#productScrollContainer') ) {
		Scroller( 5, $('#productScrollContainer .item').length );
	}
	
	
	// Homepage Such-Teaser
	$('#searchTeaser .filterCheck').change(function(){
		var url = 
			$('#productSearchLink').attr('href').replace(/#.*$/,'') +
			'#productSearch=1&page=1';
		
		var group = [];
		$('#searchTeaser .filterCheck').each(function(){
			if( this.checked ) {
				group.push( this.value );
			}
		});
		if( group.length ) {
			url += '&group=' + group.join(',');
		}
		
		$('#productSearchLink').attr('href', url);
	});
});


// Mouseover Farbzoom --------------------------------------
function prepareProductColorZoom() {
	var index = 0;
	
	// Dank IEs toller z-index implementierung werden alle Zoom-Overlays komplett ausserhalb der
	// floatenden Farbbilder erstellt und mittels absoluter positionierung über die Floats gelegt.
	// Großes Tennis :/
	$('div.productColorContainer').append( '<div class="productColorDummy"></div>' ); // Dummy um immer ein next() zu haben
	$('div.productColorZoomable').each(
		function() {
			var img = $(this).children('img');
			var src = img.attr('src').replace( /\/farben\//, '/farben-zoom/' );
			var title = img.attr('title');
			var offset = $(this).position();
			
			// Wenn das nächste Element weiter links positioniert ist, als dieses hier,
			// muss es das letzte der Zeile sein
			var next = $(this).next('div.productColorZoomable, productColorDummy');
			var addClasses = '';
			if( next.length && next.position().left < offset.left ) {
				addClasses += ' productColorZoomRight';
			}
			// Sind wir in der zweiten Zeile?
			if( offset.top > 0 ) {
				addClasses += ' productColorZoomBottom';
			}
			
			$(this).parent().prepend( 
				'<div class="productColorZoomContainer" style="top:'+offset.top+'px; left:'+offset.left+'px;">' +
					'<img class="productColorZoom'+addClasses+'" src="'+src+'" alt="" title="'+title+'"/>' +
					'<div class="productColorZoomHover" title="'+title+'"></div>' +
				'</div>'
			);
			index++;
		}
	);
	$('div.productColorContainer productColorDummy').remove();
	
	$('div.productColorZoomHover').bind( 'click', function(){
		var zoomImage = $(this).prev( 'img.productColorZoom' )
		if( zoomImage.css('display') == 'block' ) {
			zoomImage.hide(250);
		} else {
			zoomImage.show(250);
		}
	});
	$('div.productColorZoomHover').bind( 'mouseout', function(){
		 $(this).prev( 'img.productColorZoom' ).hide(250);
	});
}


// ImageZoom -----------------------------------------------
var imageZoomed = false;
var smallImage = '';
var dragX, dragY, posX, posY, minX, minY;

function prepareImageZoom() {
	$('#miniView').show().html('<div id="zoomPosition"/>');
	$('#imageZoom').bind('click', function() {
		if( !imageZoomed ) {
			
			$('#imageZoom img').attr( 'src', '/templates/zoom-out.png' );
			smallImage = $('#productImage').attr( 'src' );
			
			// load big image
			$('#productImage')
				.hide()
				.attr( 'src', $('#imageZoom').attr('href') )
				.bind('load', function() {
					minX = $('#productImageContainer').width() - $('#productImage').width();
					minY = $('#productImageContainer').height() - $('#productImage').height();
					$('#productImage')
						.css('bottom', minY/2 )
						.css('right', minX/2 )
						.show();
					$('#zoomPosition')
						.show()
						.css('right', 16)
						.css('bottom', 16);
						
				});
			
			$('#productImage')
				.css('cursor', 'move' )
				.bind('mousedown', function(e){
					dragX = e.pageX;
					dragY = e.pageY;
					posX = parseInt($('#productImage').css('right'));
					posY = parseInt($('#productImage').css('bottom'));
					$('#productImage').bind('mousemove', function(e) {
						var newX = posX - (e.pageX - dragX);
						var newY = posY - (e.pageY - dragY);
						if( newX < minX ) { newX = minX; }
						if( newY < minY ) { newY = minY; }
						if( newX > 0 ) { newX = 0 }
						if( newY > 0 ) { newY = 0 }
						$('#productImage').css('right', newX + 'px' );
						$('#productImage').css('bottom', newY + 'px' );
						
						// miniview zoom position
						var zoomPosX = (minX/2-newX)/$('#productImageContainer').width();
						var zoomPosY = (minY/2-newY)/$('#productImageContainer').height();
						$('#zoomPosition').css('right', zoomPosX*32 + 15);
						$('#zoomPosition').css('bottom', zoomPosY*37 + 15);
						return false;
					});
					return false;
				});
			$(document).bind('mouseup', function(){
				$('#productImage').unbind('mousemove');
				return false;
			});
		} else {
			$('#zoomPosition').hide();
			$('#imageZoom img').attr( 'src', '/templates/zoom-in.png' );
			$('#productImage')
				.unbind('load')
				.unbind('mousedown')
				.attr( 'src', smallImage )
				.css('right', 0)
				.css('bottom', 0)
				.css('cursor', 'default' );
			
			$(document).unbind('mouseup');
		}
		imageZoomed = !imageZoomed;
		return false;
	});
}

// Suchformular -----------------------------------
var searchTexts = {};
var searchParams = {};
var searchCurrentPage = 1;
var searchLastResultTimestamp = 0;
var searchTimeoutId = 0;

function prepareSearchForm() {

	$('#searchForm input.filterCheck').bind('click', searchEventChangeCheck );
	$('#searchForm input.filterRadio').bind('click', searchEventChangeRadio );
	$('#searchForm input.checkChildren').bind('click', searchEventChangeCheckChildren );
	$('#searchForm input.filterText').bind('keyup change', searchEventChangeText );
	
	$('#searchForm a.expand, div.filter h4, h3.filterView').bind('click', function(){
		var dropout = $(this).parent().children('div.filterDropout');
		if( dropout.css('display') != 'block' ) {
			if( $(this).hasClass('expandLevel2') ) {
				$(this).parent().parent().find('div.filterDropout').fadeOut();
				$(this).parent().parent().find('a.expand').html( "&raquo;" );
			} else {
				$('div.filterDropout').fadeOut();
				$('#searchForm a.expand').html( "&raquo;" );
			}
			dropout.fadeIn();
			var expandLink = $(this).hasClass('expand') ? $(this) : $(this).next('a.expand');
			expandLink.html( "&laquo;" );
		} else {
			if( $(this).parent().hasClass('filterDropoutLevel2') ) {
				$(this).parent().parent().find('div.filterDropout').fadeOut();
				$(this).parent().parent().find('a.expand').html( "&raquo;" );
			} else {
				$('#searchForm a.expand').html( "&raquo;" );
				$(this).parent().parent().find('div.filterDropoutLevel2').fadeOut(); // IE6
				$(this).parent().parent().find('div.filterDropout').fadeOut();
			}
		}
		return false;
	});
	
	$('div.filterDropout').append( '<a class="closeFilter" href="">x</a>' );
	$('a.closeFilter').bind('click', function() {
		if( $(this).parent().hasClass('filterDropoutLevel2') ) {
			$(this).parent().parent().find('div.filterDropout').fadeOut();
			$(this).parent().parent().find('a.expand').html( "&raquo;" );
		} else {
			$('#searchForm a.expand').html( "&raquo;" );
			$(this).parent().fadeOut();
		}
		return false;
	});
	
	resetSearch();
	setSearchFromURL();
	clearTimeout( searchTimeoutId );
	postSearchSubmit();
}

// Farbgruppen - Kinder checken
function searchEventChangeCheckChildren() {
	$(this).removeClass( 'grayed' );
	if( this.checked ) {
		$(this).parent().find('input.filterCheck')
			.each(function(){this.checked = true;})
			.each(searchEventChangeCheck);
	} else {
		$(this).parent().find('input.filterCheck')
			.each(function(){this.checked = false;})
			.each(searchEventChangeCheck);
	}
	
	postSearch();
}

// Beim ändern von Checkboxen
function searchEventChangeCheck() {
	var id = $(this).attr('id');
	var name = $('label[for='+id+']').html();
	
	// Spezialbehandlung für Farben um Farbgruppen zu checken
	if( $(this).hasClass('checkLevel2') ) {
		var filter = $(this).parent().parent().parent().parent();
		var label = $(this).parent().parent().children('label');
		var parentName = label.text();
		var parentId = label.attr('for');
		filter.children('div.faColors'+parentId).remove();

		var numChildren = 0;
		var numChecked = 0;
		var colorNames = '';
		$(this).parent().children('input.check').each(function(){
			numChildren++;
			if( this.checked ) {
				numChecked ++;
				colorNames += 
					'<div>' +
					$(this).next('label[for=' + $(this).attr('id') + ']').text() +
					'</div>'
			}
		});
		
		// Parent checken wenn Kinder aktiv sind
		if( numChecked == 0 ) {
			$(this).parent().parent().children('input.check').attr('checked', false);
		} else {
			filter.append( 
				'<div class="filterActive faColors'+parentId+'">' + 
					parentName + 
					( numChecked != numChildren ? colorNames : '' ) + 
				'</div>' 
			);
			$(this).parent().parent().children('input.check').attr('checked', true);
		}
		
		// Ausgrauen wenn nicht alle Kinder aktiv sind
		if( numChecked > 0 && numChecked != numChildren ) {
			$(this).parent().parent().children('input.check').addClass('grayed');
		} else {
			$(this).parent().parent().children('input.check').removeClass('grayed');
		}
	} else {
		var filter = $(this).parents('div.filter');
		if( this.checked ) {
			filter.append( '<div class="filterActive fa'+id+'">' + name + '</div>' );
		} else {
			filter.children('div.fa'+id).remove();
		}
	}
	
	postSearch();
}

// Beim ändern von Radiobuttons
function searchEventChangeRadio() {
	postSearch();
}

// Beim ändern von Texteingaben
function searchEventChangeText() {
	var name = $(this).attr('name');
	if( name in searchTexts && searchTexts[name] == $(this).val() ) {
		return;
	}
	searchTexts[name] = $(this).val();
	var filter = $(this).parents('div.filter');
	filter.children('div.filterActive').remove();
	if( $(this).val() ) {
		filter.append( '<div class="filterActive">' + $(this).val() + '</div>' );
	}
	postSearch();
}

// Auswahl im Suchformular aus dem Fragment-Part (#) der URL setzen
function setSearchFromURL() {
	var searchDisplay = $.cookie('searchDisplay');
	if( typeof searchDisplay != undefined ) {
		$('input.filterRadio[value='+searchDisplay+']').attr('checked', 'checked');
	}
	
	var gv = document.location.href.match(/#(.*)$/);
	if( !gv ) { return; }
	
	var extendedSearch = false;
	gv = gv[1].split('&');
	for( i in gv ) {
		p = gv[i].split('=');
		var name = p[0];
		var value = p[1];
		if( name == 'page' ) {
			searchCurrentPage = value;
		}
		else if( name == 'q' || name == 'cataloguePage' ) {
			$('input.filterText[name=' + name + ']').val( decodeURIComponent(value) ).each( searchEventChangeText );
			if( name == 'cagaloguePage' ) {
				extendedSearch = true;
			}
		}
		else {
			checkboxes = $('input.filterCheck[name^=' + name + ']');
			if( checkboxes.length ) {
				extendedSearch = true;
				checkboxes.val( value.split(',') ).each( searchEventChangeCheck );
			}
		}
	}
	
	if( extendedSearch ) {
		$('#showExtendedSearch').hide(); 
		$('#extendedSearch').show();
	}
}

function toggleExtendedSearch() {
	if( $('#showExtendedSearch').css('display') == 'block' ) {
		$('#showExtendedSearch').fadeOut(); 
		$('#extendedSearch').fadeIn();
	}
	else {
		$('#showExtendedSearch').fadeIn(); 
		$('#extendedSearch').fadeOut();
	}
	return false;
}

function resetSearch() {
	$('#searchForm input.filterCheck').val([]);
	$('#searchForm input.filterText').val('');
	$('div.filterActive').remove();
}

function searchButton() {
	$('#searchForm a.expand').html( "&raquo;" );
	$('#searchForm div.filterDropout').hide();
	postSearch();
	return false;
}

function searchChangePage( page ) {
	searchCurrentPage = page;
	postSearchSubmit();
	return false;
}

// Suchanfrage abschicken; wartet 500ms, bevor die Anfrage gestellt wird
// um den Server nicht mit unnötigen Anfragen zu überhäufen
function postSearch() {
	clearTimeout( searchTimeoutId );
	searchCurrentPage = 1;
	searchTimeoutId = setTimeout( postSearchSubmit, 500 );
}

// Baut die POST Daten aus der aktuellen Formular-Auswahl zusammen und schickt
// den Request an den Server
function postSearchSubmit() {
	$('#searchLoadIndicator').show();
	
	searchParams = {productSearch:1, page:searchCurrentPage};
	$('#searchForm input.filterCheck').each( function() {
		if( this.checked ) {
			var name = $(this).attr('name');
			if( m = name.match(/(\w+)\[\]/) ) {
				if( !(m[1] in searchParams) ) {
					searchParams[m[1]] = new Array;
				}
				searchParams[m[1]].push( $(this).val() );
				
			} else {
				searchParams[name] = $(this).val();
			}
		}
	});
	$('#searchForm input.filterText').each( function() {
		if( $(this).val() ) {
			searchParams[ $(this).attr('name') ] = $(this).val();
		}
	});
	$('#searchForm input.filterRadio').each( function() {
		if( this.checked ) {
			var name = $(this).attr('name');
			searchParams[name] = $(this).val();
			if( $(this).attr('name') == 'display' ) {
				$.cookie('searchDisplay', $(this).val(), { expires: 365, path: '/' });
			}
		}
	});
	
	for( name in searchParams ) {
		if( typeof searchParams[name] == 'object' ) {
			searchParams[name] = searchParams[name].join(',');
		}
	}
	
	// Adresszeile anpassen
	document.location.href = 
		document.location.href.replace(/#.*$/,'') +
		'#' + 
		$.objectToPostString(searchParams, [], true).replace(/%2C/g,',');
	
	// Post senden und Ergebnisliste zusammenbauen
	$.postJSON( $('#searchForm').attr('action'), searchParams, function( result ){
		$('#searchLoadIndicator').hide();
		
		// Wenn wir bereits ein Ergebnis zu einer "neueren" Suchanfrage 
		// haben, ignorieren wir dieses
		if( searchLastResultTimestamp > result.timestamp ) {
			return;
		}
		searchLastResultTimestamp = result.timestamp;
		
		// Jedes Produkt den Suchergebnissen hinzüfgen
		$('#searchResults').empty();
		for( i in result.products ) {
			var p = result.products[i];
			$('#searchResults').append(
				'<div class="searchResultItem">' +
					'<a href="' + p.link + '">' +
						'<img src="' + p.thumb + '"/>' +
					'</a>' +
					'<div class="text">' +
						'<a href="' + p.link + '">' + p.title + '</a>' + 
						'<p>' + p.summary + '</p>' +
						( p['new'] ? '<div class="newMarker">New!</div>' : '' ) +
					'</div>' + 
				'</div>'
			);
		}
		
		
		// Seitenlinks ---------------
		$('.productCount').text( result.productsTotal );
		$('.pageCount').text( result.pages.total );
		
		var numPageLinks = 9;
		var pageGroupSize = 3;
		var pageLinks = '';

		pageLinks += getPageLink( '&laquo;', 1, (result.pages.current == 1) );
		pageLinks += getPageLink( '&lsaquo;', result.pages.current - 1, (result.pages.current == 1) );
		
		// Weniger Seiten vorhanden als Pagelinks angezeigt werden sollen?
		if( result.pages.total <= numPageLinks ) {
			for( var i = 1; i <= result.pages.total; i++ ) {
				pageLinks += getPageLink( i, i, (i==result.pages.current) );
			}
		}
		else {
			// Alle Links am Anfang
			var i = 0;
			for( i = 0; i < pageGroupSize; i++ ) {
				pageLinks += getPageLink( i+1, i+1, ((i+1)==result.pages.current) );
			}
			
			// Die Links vor und hinter der aktuellen Seite
			var start = result.pages.current - 2;
			if( start <= i ) {
				start = i;
			} else {
				pageLinks += "<span>...</span>";
			}
			if( start >= result.pages.total - pageGroupSize * 2 ) start = result.pages.total - pageGroupSize * 2;
			
			for( i = start, j = 0; j < pageGroupSize && i < result.pages.total; j++, i++ ) {
				pageLinks += getPageLink( i+1, i+1, ((i+1)==result.pages.current) );
			}
			
			// Alle Links am Ende
			start = result.pages.total - pageGroupSize;
			if( start > i ) {
				pageLinks += "<span>...</span>";
			}
			for( i = start; i < result.pages.total; i++ ) {
				pageLinks += getPageLink( i+1, i+1, ((i+1)==result.pages.current) );
			}
		}
		
		pageLinks += getPageLink( '&rsaquo;', result.pages.current + 1, (result.pages.current == result.pages.total || result.pages.total == 0) );
		pageLinks += getPageLink( '&raquo;', result.pages.total, (result.pages.current == result.pages.total || result.pages.total == 0) );

		$('.pageLinks' ).html( pageLinks );
	});
}

function getPageLink( name, page, disabled ) {
	if( typeof disabled != 'undefined' && disabled ) {
		return '<strong>' + name + '</strong>';
	} else {
		return '<a href="#" onclick="return searchChangePage(' + page + ')">' + name + '</a>';
	}
}


// Scroller ------------------------------------------
var currentScrollPos = 0;
var scrollVisibleItems = 0;
var scrollTotalItems = 0;
var scrollItemHeight = 0;
var autoScrollIntervalId = 0;
function Scroller( visibleItems, totalItems ) {
	scrollVisibleItems = visibleItems;
	scrollTotalItems = totalItems;
	scrollItemHeight = parseInt($('#productScrollContainer .item').css('height'));

	$('#productScrollContainer').css('overflow', 'hidden');
	if( totalItems <= visibleItems ) {
		return;
	}
	$('#leftColumn')
		.append('<div id="scrollTop"/>')
		.append('<div id="scrollUp"/>')
		.append('<div id="scrollDown"/>')
		.append('<div id="scrollBottom"/>');
	$('#scrollDown').bind('click', scrollDown);
	$('#scrollUp').bind('click', scrollUp);
	$('#scrollTop').bind('click', scrollTop);
	$('#scrollBottom').bind('click', scrollBottom);
	
	$('#scrollUp, #scrollTop').hover(
		function(){ if( !$(this).hasClass('scrollDisabledUp') ) { $(this).addClass('scrollOverUp');} },
		function(){ $(this).removeClass('scrollOverUp'); }
	);
	
	$('#scrollDown, #scrollBottom').hover(
		function(){ if( !$(this).hasClass('scrollDisabledDown') ) { $(this).addClass('scrollOverDown');} },
		function(){ $(this).removeClass('scrollOverDown'); }
	);

	var m = [];
	if( m = document.location.href.match(/#menu=(\d+)$/) ) {
		currentScrollPos = m[1];
		if( currentScrollPos > scrollTotalItems - scrollVisibleItems ) {
			currentScrollPos = scrollTotalItems - scrollVisibleItems;
		}
		
		$('#productScrollContainer').attr('scrollTop', currentScrollPos * scrollItemHeight);
		// Und gleich nochmal, damit's IE auch kapiert :/
		$('#productScrollContainer').attr('scrollTop', currentScrollPos * scrollItemHeight);
		setScrollTargets();
	}
	setScrollButtonStates();
}

function setScrollTargets() {
	$('#productScrollContainer a, a.productTitle').attr('href', 
		function( p ) {
			return this.href.replace(/#.*$/,'') + (currentScrollPos? '#menu='+currentScrollPos : '' );
		}
	);
}

function scrollTop() {
	clearInterval( autoScrollIntervalId );
	currentScrollPos = 0;
	scrollToCurrentProduct();
	return false;
}

function scrollBottom() {
	clearInterval( autoScrollIntervalId );
	currentScrollPos = scrollTotalItems - scrollVisibleItems;
	scrollToCurrentProduct();
	return false;
}

function scrollDown() {
	clearInterval( autoScrollIntervalId );
	currentScrollPos++;
	if( currentScrollPos > scrollTotalItems - scrollVisibleItems ) {
		currentScrollPos = scrollTotalItems - scrollVisibleItems;
	}
	scrollToCurrentProduct();
	return false;
}

function scrollUp() {
	clearInterval( autoScrollIntervalId );
	currentScrollPos--;
	if( currentScrollPos < 0 ) {
		currentScrollPos = 0;
	}
	scrollToCurrentProduct();
	return false;
}

function scrollToCurrentProduct() {
	var scrollPosition = currentScrollPos * scrollItemHeight;
	$('#productScrollContainer').stop();
	$('#productScrollContainer').animate({scrollTop: scrollPosition}, 250);
	
	setScrollButtonStates();
	setScrollTargets();
}

function setScrollButtonStates() {
	if( currentScrollPos == 0 ) {
		$('#scrollUp, #scrollTop')
			.addClass( 'scrollDisabledUp' )
			.removeClass( 'scrollOverUp' );
	} else {
		$('#scrollUp, #scrollTop').removeClass( 'scrollDisabledUp' );
			
	}
	
	if( currentScrollPos == scrollTotalItems - scrollVisibleItems ) {
		$('#scrollDown, #scrollBottom')
			.addClass( 'scrollDisabledDown' )
			.removeClass( 'scrollOverDown' );
	} else {
		$('#scrollDown, #scrollBottom').removeClass( 'scrollDisabledDown' );
	}
}

function autoScroll() {
	currentScrollPos++;
	if( currentScrollPos > scrollTotalItems - scrollVisibleItems ) {
		currentScrollPos = 0;
	}
	scrollToCurrentProduct();
}


// generics ---------------------------------------------------
$.postJSON = function(url, data, callback) {
	if( typeof data == 'object' ) {
		data = $.objectToPostString( data, [], true );
	}
	$.post(url, data, callback, "json");
};

$.objectToPostString = function( data, path, first ) {
	var s = "";
	if( data && data.length ) {
		var a = data;
		data = {};
		for( var i = 0; i < a.length; i++ ) {
			data[i] = a[i];
		}
	}
	
	for( key in data ) {
		path.push( key );
		if( typeof data[key] == 'object' ) {
			s += $.objectToPostString( data[key], path, first );
		} else {
			if( !first ) {
				s += '&';
			} else {
				first = false;
			}
			if( path.length == 1 ) {
				s += key + '=' + encodeURIComponent(data[key]);
			} else {
				s += path[0] + '[' + path.slice(1).join('][') + ']=' + encodeURIComponent(data[key]);
			}
		}
		path.pop();
	}
	return s;
};

$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};