// JavaScript Document

function downloadImage() {
	// search for cookie
	// if one exists, do MC check and allow download if all ok
	
	// otherwise show image form
	//toggleImageForm();
	toggleForm($('#imageQuickForm'), $('#downloadbtn'));
}

function toggleForm(form, title) {
	//
	//var form = $('#imageQuickForm');
	if (form.css("display") == "block") {
		// hide form
		form.css("display", "none");
		if (title) {
			title.attr("class", "");
		}
	} else {
		// show form
		form.css("display", "block");
		if (title) {
			title.attr("class", "white");
		}
	}
}

// resize functions
  function fitArea(target, wid, hei, getWid) {
    var originalWid = target.width();
	if (getWid > 0) {
		originalWid = getWid;
	}
	//var originalHei = target.height();
	var originalHei = 800;
	target.width(wid);
	var scaleRatio = wid/originalWid;
	target.height(Math.round(originalHei*scaleRatio));
	if (target.height() > hei) {
	  scaleRatio = hei/originalHei;
	  target.height(hei);
	  target.width(Math.round(originalWid*scaleRatio));
	}
  }
  
  function setDimensionsTofitArea(target, maxWid, maxHei, getWid, getHei) {
	//
	var scaleRatio = maxWid/getWid;
	var newHei = Math.round(getHei*scaleRatio);
	if (newHei > maxHei) {
	  scaleRatio = maxHei/getHei;
	  newWid = Math.round(getWid*scaleRatio);
	  target.attr("width", newWid);
	  target.attr("height", maxHei);
	} else {
	  target.attr("width", maxWid);
	  target.attr("height", newHei);	
	}
  }
  
  function fillArea(target, wid, hei, getWid) {
    var originalWid = target.width();
	if (getWid > 0) {
		//originalWid = getWid;
	}
	//var originalHei = target.height();
	var originalHei = 160;
	target.width(wid);
	var scaleRatio = wid/originalWid;
	target.height(Math.round(originalHei*scaleRatio));
	if (target.height() < hei) {
	  scaleRatio = hei/originalHei;
	  target.height(hei);
	  target.width(Math.round(originalWid*scaleRatio));
	}
  }

  function resizeWorkArea(){
  	//
	//$("#main").width($(window).width()-203);
  }
  
  function fitAllImages(){
	//
	var counter = 0;
	//
	$('.left-image').each(function() {
	  //
	  var left = $(this).children('img');
	  var right = $(this).next().children('img');
	  //
	  //if (counter < 1) { alert("width = "+parseInt($(right).css("width").replace("px", ""))); }
	  //
	  var leftOldWid = cssToInt($(left).css("width"));
	  var leftOldHei = cssToInt($(left).css("height"));
	  if ($(right).length) {
	  	var rightOldWid = cssToInt($(right).css("width"));
	  	var rightOldHei = cssToInt($(right).css("height"));
	  }
	  //
	  //if (leftOldWid > 0) {
		if ($(right).length) {
		  var leftProportion = leftOldWid / (leftOldWid+rightOldWid);
		  //alert(leftProportion);
		  var leftWid = ($(window).width()-211)*leftProportion;
		} else {
		  var leftWid = $(window).width()-203;
		}
		setDimensionsTofitArea($(left), leftWid, $(window).height()-100, leftOldWid, leftOldHei);
		if ($(right).length) {
			setDimensionsTofitArea($(right), $(window).width()-(211+leftWid), $(window).height()-100, rightOldWid, rightOldHei);
			$(this).next().css("marginLeft", cssToInt($(left).css("width"))+4);
		}	
	  //}							   
		counter++;						   
	});
	  
  }
  
  function cssToInt(value) {
	//  
	return parseInt(value.replace("px", "")) 
  }
  
  function position(target, container, align) {
  
	if (align=="center") {
		//alert(target.width());
	   target.css("margin-left", (container.width()/2)-(target.width()/2));
	   //target.css("margin-top", (container.height()/2)-(target.height()/2));
	}
}

function updateImageNav(opts) {
	//
	var caption = $('#image-holder').children(':eq('+opts.currSlide+')').children(':first').children(':first').attr("alt");
	$('#caption').html(nl2br(caption));
	$('#counter').html((opts.currSlide+1)+' / '+opts.slideCount);
	window.location.hash = "#"+opts.currSlide;
	currentImage = opts.currSlide;
}

function quickNav(imageid) {
	//
	var caption = paths_to_add[imageid][2];
	$('#caption').html(caption);
	$('#counter').html((imageid+1)+' / '+paths_to_add.length);
}

function setFirstImage() {
	//	
	$('#image-holder').children(':eq('+firstImage+')').attr("id", "first");
	
}

function enlarge(imageid) {
	//
	hideThumbGrid();
	$('#downloadbtn').css("display", "inline");
	addImgSrc(imageid);
	$('#image-holder').fadeIn(600);
	//
	firstImage = imageid;
	past = -1;
	pastSlide = imageid;
	$('#image-holder').cycle(imageid); 
}



function addNextSlide(curr,next,opts,dummy,noPast) {
	//
	if ($('#preload').css("display") == "block") {
		$('#preload').fadeOut(600);
	}
	if ($('#caption').length) {
		updateImageNav(opts);
	}
	//
	// if first image loaded is beyond the number of images loaded by PHP..
	if (firstImage >= num_images_init && firstImage == opts.currSlide) {
		addImgSrc(firstImage);
	}
	// if this is the very first image loaded, add the next one too
	if (firstImage == opts.currSlide) {
		pastSlide = opts.currSlide;
	}
	//
	var future = Math.max(num_images_init-firstImage, 1);
	//
	var nextSlide = opts.nextSlide-2;
	var nextSlideToLoad = nextSlide+future;
	var maxSlides = paths_to_add.length;
	if (nextSlideToLoad >= maxSlides) {
		nextSlideToLoad = future-(maxSlides-nextSlide);
	}
	//alert(firstImage+" / "+opts.currSlide+" / "+opts.nextSlide);
	addImgSrc(nextSlideToLoad);
	//
	preloadStarted = true;
	//
	if (noPast!=true) {
		addPrevSlide();
	}
	//
	if (future<num_images_init) {
		//
		var catchUp=num_images_init-(future+1);
		firstImage=catchUp;
		addNextSlide('','',opts,'',true);
	}
}

function addPrevSlide() {
	//	
	for (i=0; i<Math.ceil(num_images_init/2); i++) {
		pastSlide+=past;
		if (pastSlide<num_images_init) {	
			past = -1;
			pastSlide = paths_to_add.length+past;
		} 
		addImgSrc(pastSlide);
	}
}

function addImgSrc(imageid) {
	//
	var left = $('#image-holder').children(':eq('+imageid+')').children('.left-image').children(':first');
	if ($(left).length) {
		if ($(left).attr("src") == "") {
			$(left).attr("src", paths_to_add[imageid][0]);
			if (paths_to_add[imageid][1] != "") {
				var right = $(left).parent().next().children(':first');
				$(right).attr("src", paths_to_add[imageid][1]);
			}
		}
	}
}


function createThumbGrid() {
	//	
	window.location.hash = "#thumbs";
	//
	// hide images
	$('#image-holder').fadeOut(600);
	//
	var i=0;
	//
	$(paths_to_add).each(function(){
		//
		var path = $(this)[0];
		var partnerpath = $(this)[1];
		var caption = $(this)[2];
		//
		$('#thumbnails').append("<div class='foliothumb'><a href='#"+i+"' onclick='enlarge("+i+");' ><img id='thumbnail_"+i+"' style='display:none;' src='"+path.replace("low res", "thumbs")+"' alt='"+caption+"' border='0' onmouseover='quickNav("+i+");' /></a></div>");
		//
		$('#thumbnail_'+i).load(function()
			{
				fillArea($(this), 116, 90);
				position($(this), $(this).parent().parent(), "center");
				$(this).fadeIn(600);
			}).each(function(){ 	// IE workaround as load doesn't fire on cached images
				if(this.complete && (jQuery.browser.msie)) {
					$(this).trigger("load");
				}
			});
		//
		$('#thumbnail_'+i).error(function(){
			//
			$(this).parent().parent().css("width", 0);
			$(this).parent().parent().css("margin-right", 0);
		});
		//
		// partner
		if (partnerpath) {
			$('#thumbnails').append("<div class='foliothumb'><a href='#"+i+"' onclick='enlarge("+i+");' ><img id='thumbnail_p_"+i+"' style='display:none;' src='"+partnerpath.replace("low res", "thumbs")+"' alt='"+caption+"' border='0' onmouseover='quickNav("+i+");' /></a></div>");
			//
			$('#thumbnail_p_'+i).load(function()
				{
					fillArea($(this), 116, 90);
					position($(this), $(this).parent().parent(), "center");
					$(this).fadeIn(600);
				}).each(function(){ 	// IE workaround as load doesn't fire on cached images
					if(this.complete && (jQuery.browser.msie)) {
						$(this).trigger("load");
					}
				});
			//
			$('#thumbnail_p_'+i).error(function(){
				//
				$(this).parent().parent().css("width", 0);
				$(this).parent().parent().css("margin-right", 0);
			});
		}
		//
		i++;
	});
	//
	$('.book-btn').each(function(){
		$(this).attr("href", $(this).attr("href")+"#thumbs"); 
	});
	//
	//$('#thumbnails').fadeIn(600);
	$('#thumbnails').css("display", "block");
	$('#thumbs-btn').attr("class", "clickable white");
	$('#preload').css("display", "none");
	$('#downloadbtn').css("display", "none");
	//
	//updateImageNav(currentImage);
}


function hideThumbGrid() {
	//
	$('#thumbs-btn').attr("class", "clickable");
	//$('#thumbnails').fadeOut(600);
	//$('#thumbnails').css("display", "none");
	$('#thumbnails').empty();
	$('.book-btn').each(function(){
		$(this).attr("href", $(this).attr("href").replace("#thumbs",""));
	});
	displayThumbs = 'off';
}

  
 // alter class depending on thumbnail position
  function addKeylines(){
    $(".thumb").addClass(function() {
	  var p = $(this);
      var position = p.position();
	  if ( position.top > 100) {
	    return "top-line";
	  }
	});
  } 
  
  
  function ie8SafePreventEvent(e){
    if(e.preventDefault){ e.preventDefault()}
    else{e.stop()};

    e.returnValue = false;
    e.stopPropagation();        
}
  
function toggleInfo() {
	//
	if ($('#info').css("display") == "block") {
		// hide elements
		$('#info').css("display", "none");
		$('#backbtn').css("display", "none");
		// show elements
		$('#image-nav').css("display", "block");
		$('#books').css("display", "block");
		$('#downloadbtn').css("display", "block");
		$('#image-holder').css("display", "block");
		if (!$('#leftimg').css("display")) {
			//enlarge(0);	
		}
		//resizeWorkArea();
		//$('#preload').css("display", "block");
	} else {
		// set back href to current image
		$('#back').attr("href","#"+currentImage);
		window.location.hash = "#biog";
		// hide elements
		$('#image-nav').css("display", "none");
		$('#books').css("display", "none");
		$('#downloadbtn').css("display", "none");
		$('#image-holder').css("display", "none");
		//$('#preload').css("display", "none");
		if ($('#thumbnails').css("display") != "none") {
			hideThumbGrid();
		}
		// show elements
		$('#info').css("display", "block");
		$('#backbtn').css("display", "block");
	}
}
  
function subscribeDivert(assetType) {
	//
	var email = $('#email').val();
	if ($('input[name=rememberme]').attr('checked') == true) {
		$.cookie("ep_email", email, { expires: 30 });
	} else {
		$.cookie("ep_email", null);
	}
	// create query string
	var query = "&region="+currentRegion;
	query += "&email="+email;
	query += "&assetType="+assetType;
	query += "&stat="+user_stat;
	
	if (assetType == "hires") {
		query += "&leftimg="+paths_to_add[currentImage][0];
		query += "&rightimg="+paths_to_add[currentImage][1];
		query += "&div="+division;
		query += "&artist="+artist_name;
		query += "&book="+book_name;
		query += "&imageid="+currentImage;
	}
	else if (assetType == "pdf") {
		for (var d=0; d<downloads.length; d++) {
			query += "&foliopath_"+d+"="+downloads[d];
		}
		query += "&num_folios="+downloads.length;
	}
	//
	window.location.replace(url_prefix+'subscribe.php?'+query);
	
}


function subscribe(assetType) {
	//
	// validate form
	if ($('#email').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your email</p>');
		$('#email').focus();
	} else if ($('#first_name').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your first name</p>');
		$('#first_name').focus();
	} else if ($('#last_name').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your last name</p>');
		$('#last_name').focus();
	} else if ($('#email').val() != $('#confirmemail').val()) {
		showFailed('subscribe', '<p>The email addresses entered do not match</p>');
		$('#email').focus();
	} else if ($('#company').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your company name</p>');
		$('#company').focus();
	} else if ($('#phone').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your phone number</p>');
		$('#phone').focus();
	} else if ($('#occupation').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your occupation</p>');
		$('#occupation').focus();
	} else if ($('#country').val().length < 1) {
		showFailed('subscribe', '<p>Please enter your country</p>');
		$('#country').focus();
	} else {
		//
		toggleForm($('#pleasewait'));
		//
		var email = $('#email').val();
		if ($('input[name=rememberme]').attr('checked') == true) {
			$.cookie("ep_email", email, { expires: 30 });
		} else {
			$.cookie("ep_email", null);
		}
		//
		var query = $('#subscribe').serialize();
		//
		$.ajax({
			type: "POST",
			url: "php/download_sequence/addUpdateMember.php",
			data: query,
			success: function(xml) {
				toggleForm($('#pleasewait'));
				if (assetType == 'pdf') {
					showThanks('folios', xml);
				} else {
					showThanks('artist', xml);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//
				toggleForm($('#pleasewait'));
				showFailed('folios', 'Sorry, we are currently experiencing problems with our system. Please call us on one of the above numbers for assistance.');
			}
		});
	}
}

function signup(form) {
	//
	// validate form
	if ($('#mce-EMAIL').val().length < 1) {
		showFailed('signup', '<p>Please enter your email</p>');
		$('#mce-EMAIL').focus();
	} else if ($('#mce-FNAME').val().length < 1) {
		showFailed('signup', '<p>Please enter your first name</p>');
		$('#mce-FNAME').focus();
	} else if ($('#mce-LNAME').val().length < 1) {
		showFailed('signup', '<p>Please enter your last name</p>');
		$('#mce-LNAME').focus();
	} else if ($('#mce-EMAIL').val() != $('#confirmemail').val()) {
		showFailed('signup', '<p>The email addresses entered do not match</p>');
		$('#mce-EMAIL').focus();
	} else if ($('#mce-COMPANY').val().length < 1) {
		showFailed('signup', '<p>Please enter your company name</p>');
		$('#mce-COMPANY').focus();
	} else if ($('#mce-PHONE').val().length < 1) {
		showFailed('signup', '<p>Please enter your phone number</p>');
		$('#mce-PHONE').focus();
	} else if ($('#mce-ROLE').val().length < 1) {
		showFailed('signup', '<p>Please enter your occupation</p>');
		$('#mce-ROLE').focus();
	} else {
		//
		toggleForm($('#pleasewait'));
		//
		$.ajax({
			type: "POST",
			url: "php/download_sequence/subscribeMember.php",
			data: form.serialize(),
			success: function() {
				showThanks('signup');
			},
			error: function() {
				alert('post error');
				showFailed('signup', '<p>Sorry, we are currently experiencing problems with our system. Please call us on one of the above numbers for assistance.</p>');
			}
		});
	}
}

  
function sendEnquiry(form) {
	//
	// validate form
	if ($('#fname').val().length < 1) {
		showFailed('contact', '<p>Please enter your first name</p>');
		$('#fname').focus();
	} else if ($('#lname').val().length < 1) {
		showFailed('contact', '<p>Please enter your last name</p>');
		$('#lname').focus();
	} else if ($('#email').val().length < 1) {
		showFailed('contact', '<p>Please enter your email</p>');
		$('#email').focus();
	} else if ($('#email').val() != $('#confirmemail').val()) {
		showFailed('contact', '<p>The email addresses entered do not match</p>');
		$('#email').focus();
	} else if ($('#msg').val().length < 1) {
		showFailed('contact', '<p>Please enter a message</p>');
		$('#msg').focus();
	} else {
		//
		$.ajax({
			type: "POST",
			url: "php/ep_enquiry.php",
			data: form.serialize(),
			success: function() {
				showThanks('contact');
			},
			error: function() {
				alert('post error');
				showFailed('contact', '<p>Sorry, we are currently experiencing problems with our system. Please call us on one of the above numbers for assistance.</p>');
			}
		});
	}
}

function showThanks(page, xml) {
	//
	switch (page) {
		
		case 'contact': case 'signup' :
			$('#fail').empty();
			$('#fail').css("display", "none");
			$('#enquiryForm').css("display", "none");
			$('#thanks').css("display", "block");
			break;
			
		case 'folios' : case 'artist' :
			//
			var msg = ""
			$(xml).find("response").each(function(){
				msg = $(this).attr("msg");									  
			});
			//								  
			$('#fail').empty();
			$('#fail').css("display", "none");
			$('#folioForm').css("display", "none");
			$('#intro').css("display", "none");
			$('#complete').empty();
			$('#complete').append(msg);
			$('#confirm').css("display", "block");
			break;
		
		default : null;
	}		
}

function showFailed(page, msg) {
	//
	switch (page) {
		
		case 'contact': case 'subscribe': case 'signup' :
			$('#fail').empty();
			$('#fail').append(msg);
			$('#fail').css("display", "block");
			break;
			
		case 'folios':							  
			$('#folioForm').css("display", "none");
			$('#intro').css("display", "none");
			$('#complete').empty();
			$('#complete').append(msg);
			$('#confirm').css("display", "block");
			break;	
		
		default : null;
	}		
}
  
  
function getDownload(assetType) {
	//
	toggleForm($('#pleasewait'));
	//
	var email = $('#email').val();
	if ($('input[name=rememberme]').attr('checked') == true) {
		$.cookie("ep_email", email, { expires: 30 });
	} else {
		$.cookie("ep_email", null);
	}
	// create query string
	var query = "email="+email;
	query += "&assetType="+assetType;
	
	if (assetType == "hires") {
		query += "&leftimg="+paths_to_add[currentImage][0];
		query += "&rightimg="+paths_to_add[currentImage][1];
	}
	else if (assetType == "pdf") {
		for (var d=0; d<downloads.length; d++) {
			query += "&foliopath_"+d+"="+downloads[d];
		}
		query += "&num_folios="+downloads.length;
	}
	// please wait!
	//recordCookieData(main_region.info_holder.email_form);
	//
	$.ajax({
		type: "POST",
		url: "php/download_sequence/listMembers.php",
		data: query,
		success: function(xml) {
			toggleForm($('#pleasewait'));
			checkMLStatus(xml, assetType);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//
			toggleForm($('#pleasewait'));
			alert('Error getting download');
		}
	});
}


function checkMLStatus(xml, assetType) {
	
	var output = "";
	
	$(xml).find("response").each(function(){
		//
		// person is subscribed
		if ($(this).attr("msg") && $(this).attr("msg").length>0) {
			//	
			output = $(this).attr("msg");
			$('#complete').empty();
			$('#complete').append(output);
		}
		else if ($(this).attr("type") == "sub") {
			if ($(this).attr("stat") == "Allowed" || $(this).attr("stat") == "Pending" || $(this).attr("stat") == "Reapplied") {
				output = "Thank you, you have been sent an email with a link to download this file.";
				$('#complete').empty();
				$('#complete').append(output);
				toggleForm($('#folioQuickForm'));toggleForm($('#imageQuickForm'));
				toggleForm($('#confirmQuick'));
				setTimeout("$('#confirmQuick').fadeOut(600);", 4000);
				setTimeout("$('#folioQuickForm').fadeIn(600);", 4000);
				setTimeout("$('#imageQuickForm').fadeIn(600);", 4000);
			}
			else if ($(this).attr("stat") == "Blocked") {
				output = "Sorry, these files are not currently available for download";
				$('#complete').empty();
				$('#complete').append(output);
				toggleForm($('#folioQuickForm'));toggleForm($('#imageQuickForm'));
				toggleForm($('#confirmQuick'));
				setTimeout("$('#confirmQuick').fadeOut(600);", 4000);
				setTimeout("$('#folioQuickForm').fadeIn(600);", 4000);
				setTimeout("$('#imageQuickForm').fadeIn(600);", 4000);
			}
			// status is 'suspended' (disallowed)
			else {
				output = "Please update and confirm your details in order to proceed with the download";
				$('#further').empty();
				$('#further').append(output);
				toggleForm($('#folioQuickForm'));toggleForm($('#imageQuickForm'));
				user_stat = $(this).attr("stat");
				toggleForm($('#askSignup'));
				//createProfileForm("Reapplied", assetType, formsX);
			}							
		}
		// person has unsubscribed or is new, they need to re-subscribe
		else if ($(this).attr("type") == "unsub" || $(this).attr("type") == "new") {
			output = "You will need to subscribe to our mailing list in order to download images";
			if ($(this).attr("type") == "unsub") { user_stat = "Resubscribed"; } else { user_stat = "Pending"; }
			$('#further').empty();
			$('#further').append(output);
			toggleForm($('#folioQuickForm'));toggleForm($('#imageQuickForm'));
			toggleForm($('#askSignup'));
			//createProfileForm(stat, assetType);
		}
		else {
			// couldn't get a recognised message from mailchimp
			output = "Sorry, we are currently experiencing difficulties with the website, please try again later or call the office on +44 (0)207 722 3444";	
			alert(output);
		}
		//formatText(main_region.info_holder.info, output, "AkzGrotEmbed", 11, -1, 0, white, "left");
	});
	//
	//alert(output);
}
  
  
// ** functions to download PDFs **

function toggleDownload(pdfpath, element) {
	//alert(element);
	//
	$(element).empty();
	//
	if (!in_array(pdfpath, downloads)) {
		downloads.push(pdfpath);
		$(element).append('<span class="green">Folio selected</a>');
	} else {
		downloads = jQuery.grep(downloads, function(value) {
			return value != pdfpath;
		});	
		$(element).append('Select');
	}
}


function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}

function nl2br (str, is_xhtml) {
    // Converts newlines to HTML line breaks  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/nl2br
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin\nvan\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '\nOne\nTwo\n\nThree\n'
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
 
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
