

//are we using IE6?
var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

//when the document loads...
$(function(){
	//set everything that has a class of btnable with the correct events
	//these events mearly add an "over" class onmouseover and removes it onmouseout 
	setupBtnable();
	
	//easy preloading of CSS images
	//$.preloadCssImages();
	
});

function setupBtnable(){
	$(".btnable").mouseover(function(){
		var obj = $(this);
		if(obj.hasClass("over") == false && obj.hasClass("selected") == false)
			obj.addClass("over");
	})
	$(".btnable").mouseout(function(){
		var obj = $(this);
		if(obj.hasClass("over") == true)
			obj.removeClass("over");
	});
}

/* clear the contents from the textbox if they dont match the origional*/
function clearText(which, origional){
	var val = $(which).val();
	if(origional == val){
		$(which).val('');
	}
}

/* set the text back to the origional if it's empty */
function setText(which, origional){
	var val = $(which).val();
	if(val == ''){
		$(which).val(origional);
	}
}

/* make the (textbox) password into a password password box */
function transformPassword(which){
	//$(which).attr("type", "password");
	$(which).css("display", "none");
	$(which).next().attr("style", "").focus();	
}

/* page-specific js */
/* my-details */
function selectRoom(id){
	/* show a room's drop down based on the selected room 
	* id is the id of the select to now show 
	*/
	$(".roomselect").css("display", "none");
	$("#"+id).css("display", "block");	
}

var signinHtml = '<div id="signlogpop"><form method="post" action="/login"><input type="hidden" id="goto" name="goto" value=""><div style="float:left;width:130px;"><img src="/images/sproost_word.gif" /></div><div style="float:left;width:150px;font-size:25px;text-align:left;padding-left:12px;">sign in</div><div class="left form_label">email address</div><div class="right"><input type="text" name="email" /></div><div class="left form_label">password</div><div class="right"><input type="password" name="password" /></div><div class="left">&nbsp;</div><div class="right"><input type="submit" value="sign in" />&nbsp;&nbsp;&nbsp;<a href="#" onclick="cancelSignin();return false;">Cancel</a></div><div class="left">&nbsp;</div><div class="right"><a href="#signup" onclick="gotoSignUp()">Need to sign up?</a><br><a href="#forgot" onclick="gotoForgot()">Forgot your password?</a></div><div id="error"></div></form></div>';

function signIn(goto){
	//window.location.hash = "login";
	showPopup(signinHtml, true);
	setTimeout(function(){
		$("input[name='email']").focus();
		
		if(!goto && !loginAction){
			goto = window.location.pathname.substr(1);
		}else if(goto){
			loginAction = goto;
		}else if(loginAction){
			goto = loginAction;
		}
		
		$("#signlogpop #goto").val(goto);
		//}
		
	}, 500);
	$("#signlogpop input[type='submit']").click(function(){
		$("#signlogpop #error").css('visibility', 'hidden');
		$.ajax({
		   	type: "POST",
		   	url: "/ajax/login",
		   	data: "email="+$("input[name='email']").val()+"&password=" + $("input[name='password']").val(),
		   	success: function(msg){
		   		if(msg == ''){
					$("#signlogpop form").unbind();
					$("#signlogpop form").submit();
				}else{
					$("#signlogpop #error").html(msg);
					$("#signlogpop #error").css('visibility', 'visible');
				}
			}
		});
	});
	$("#signlogpop form").submit(function(){
		return false;
	});
}

var signupAction;
var loginAction;

function gotoSignUp(goto){

	$("#signlogpop").replaceWith(signupHtml);
	
	setTimeout(function(){
		$("input[name='email1']").focus();
		if(!goto && !signupAction){
			goto = window.location.pathname.substr(1);
		}else if(goto){
			signupAction = goto;
		}else if(signupAction){
			goto = signupAction;
		}
		
		$("#signlogpop #goto").val(goto);
		
		//}
		
	}, 500);
	showPopup(signupHtml, true);
	$("#signlogpop form").submit(function(){
		$("#signlogpop #error").css('visibility', 'hidden');
		
		if($("#signupform input[name='password1']").val() != $("#signupform input[name='password2']").val()){
			$("#signlogpop #error").html('The two passwords do not match');
			$("#signlogpop #error").css('visibility', 'visible');
			return false;
		}
		var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		if(regex.test($("#signupform input[name='email1']").val()) == false){
			$("#signlogpop #error").html('That is not a valid email');
			$("#signlogpop #error").css('visibility', 'visible');
			return false;
		}
		if($("#signupform input[name='password1']").val().length < 5 || $("#signupform input[name='password1']").val().length > 25){
			$("#signlogpop #error").html('Password must be between 5 and 25 characters');
			$("#signlogpop #error").css('visibility', 'visible');
			return false;
		}
		
	});
	
	$("#signlogpop input[name='email1']").blur(function(){
		$.ajax({
		   	type: "POST",
		   	url: "/ajax/emailExists",
		   	data: "email="+$("input[name='email1']").val(),
		   	success: function(msg){
		   		if(msg == 'true'){
					$("#signlogpop #error").html("That email already has an account.");
					$("#signlogpop #error").css('visibility', 'visible');
					$("#signlogpop input[type='submit']").attr("disabled","disabled");
				}else{
					$("#signlogpop #error").css('visibility', 'hidden');
					$("#signlogpop input[type='submit']").removeAttr("disabled");
				}
			}
		});
	});
}

function gotoSignIn(){
	signIn();
	//$("#signlogpop").replaceWith(signinHtml);
}

var signupHtml = '<div id="signlogpop"><form id="signupform" method="post" action="/join"><input type="hidden" id="goto" name="goto" value=""><div style="float:left;width:130px;"><img src="/images/sproost_word.gif" /></div><div style="float:left;width:150px;font-size:25px;text-align:left;padding-left:5px;">sign up</div><div style="clear:both;padding:10px 0 10px 8px;text-align:left;"><p>Sign up so we can remember your style and the rooms you create. We will never spam you.</p></div><div class="left form_label">email address</div><div class="right"><input type="text" name="email1" id="emaill" /></div><div class="left form_label">choose a password</div><div class="right"><input type="password" name="password1" id="password1" /></div><div class="left form_label">confirm password</div><div class="right"><input type="password" name="password2" id="password2" /></div><div class="left">&nbsp;</div><div class="right"><input type="submit" value="sign up" />&nbsp;&nbsp;&nbsp;<a href="#" onclick="cancelSignin();return false;">Cancel</a></div><div class="left">&nbsp;</div><div class="right"><a href="#login" onclick="gotoSignIn()">Already have an account?</a></div><div id="error"></div></form></div>';

function signUp(){
	//window.location.hash = "signup";
	gotoSignUp();
}

function cancelSignin(){
	//if(window.location.pathname != "/"){
	//	window.location.href= "/";
	//}
	hidePopup();
}

var forgotHtml = '<div id="signlogpop"><form method="post" action="/account/recover"><div style="float:left;width:130px;"><img src="/images/sproost_word.gif" /></div><div style="float:left;width:150px;font-size:25px;text-align:left;padding-left:12px;">reminder</div><div class="left form_label">email address</div><div class="right"><input type="text" name="email" id="emaill" /></div><div class="left form_label">&nbsp;</div><div class="right">no worries - we\'ll email you instructions to reset your password</div><div class="left">&nbsp;</div><div class="right"><input type="submit" value="Send it" />&nbsp;&nbsp;&nbsp;<a href="#" onclick="cancelSignin();return false;">Cancel</a></div><div class="left">&nbsp;</div><div class="right"><a href="#login" onclick="gotoSignIn()">< back to sign in</a></div><div id="error"></div></form></div>';

function gotoForgot(){
	$("#signlogpop").replaceWith(forgotHtml);
}


function submitMyDetails(){
	var val = $("input[name='budget']").val();
	if(val.substr(0,1) == "$"){
		val = val.substr(1, val.length-1);
	}
	
	val = val.replace(/\,/g, '');
	val = val.replace(/^\s*|\s*$/g,'');

	var dig = /^\d{0,10}$/;
	if(val.search(dig) == -1){
		$(".budgeterror").css("display", "block");
		$("input[name='budget']").val('e.g. $7,500').css('color', '#aaaaaa');
		return;
	}
	$("input[name='budget']").val(val);
	$("#popupcontent").html('One moment please!<br /><br /><img src="images/green-loading.gif" /><br /><br />We\'re figuring out what products you like');
	$("#shadow").fadeTo(5, .70);
	$("#shadow").fadeIn();
	
	$("#popup").css("width", "300px");
	
	$("#popupwrap").css("top", parseInt($(window).scrollTop()) + 150 + "px");
	$(window).scroll(function(){
		$("#popupwrap").css("top", parseInt($(window).scrollTop()) + 150 + "px");
	});
	$("#popupwrap").fadeIn();
	
	$.ajax({
	   type: "POST",
	   url: "/my-details",
	   data: $("#mydetails").serialize(),
	   success: function(data){
			window.location='/roosts';
	   }
	 });
	
}
/* end my-details */
/* engine zoom & highlight */
function transImage(id){
	if($("#img" + id).hasClass("on")){
		$("#img" + id).removeClass("on");
		$("#img" + id).fadeTo(5, 1);
	}else{
		$("#img" + id).fadeTo(5, .66);
		$("#img" + id).addClass("on");
	}
}
var imageZoomed = false;
function zoomImage(id){
	if(imageZoomed){
		//there is an image zoomed! the object is in the imageZoomed variable
		$("#temp").unbind("click");
		//animate position back
		$("#temp").animate({
			"left":parseInt(currentLeft) + "px",
			"top":parseInt(currentTop) + "px"
		});
		//animate back to 300
		$("#temp img").animate({
			"width":"300px"
		}, function(){
			//show origional
			imageZoomed.css({
				"visibility":"visible"
			});
			//remove the temp
			$("#temp").remove();
			//no longer zoomed
			imageZoomed = false;
		});
		$(window).unbind('click');
		
	}else{
		//no image zoomed
		$("body").append("<div id='temp'><img src='"+ $("#"+id).attr("src") +"' width='300'></div>");
		currentLeft = $("#"+id).offset().left;
		currentTop = $("#"+id).offset().top;
		
		var currentHeight = $("#"+id).height();
		
		//align and show the temp div
		$("#temp").css({
			"top":currentTop,
			"left":currentLeft,
			"display":"block",
			"z-Index":"1000"
		});
		//hide the origional image
		$("#"+id).css({
			"visibility":"hidden"
		});
		
		//animate the temp image
		//width
		$("#temp img").animate({
			"width":"500px"
		}, function(){
			$("#temp").click(function(){
				zoomImage(id);
			});
			$(window).click(zoomImage);
		});
		
		//location
		$("#temp").animate({
			"left":parseInt(currentLeft) - 100 + "px",
			"top": $(window).scrollTop() + 45 //"60px"
		});
		
		
		imageZoomed = $("#"+id);
		
	}
}

function showPopup(HTMLcontent, showShadow, resize){

	$("#popupcontent").html(HTMLcontent);

	if(showShadow){
		$("#shadow").fadeTo(5, .65);
		$("#shadow").fadeIn();
		$("#shadow").click(function(){
			hidePopup();
		});
	}
	
	if(resize){
		$("#popupwrap").css({
			"visibility":"hidden",
			"display":"block"
		});
	
		var newWidth = $("#popupcontent").width();
		
		$("#popupwrap").css({
			"display":"none",
			"visibility":"visible"
		});
		
		$("#popup").css({
			"width": parseInt(newWidth) + 25
		});
	}
	$("#popupwrap").css("top", parseInt($(window).scrollTop()) + 150 + "px");
	$(window).scroll(function(){
		$("#popupwrap").css("top", parseInt($(window).scrollTop()) + 150 + "px");
	});
	
	$("#popupwrap").fadeIn();
}
function hidePopup(){
	$("#shadow").fadeOut();
	$("#popupwrap").fadeOut();
}

function comingSoon(){
	showPopup('Check back later, this is coming soon...<br><br> <input type="submit" value="OK" onclick="hidePopup();">', true, true);
}

/*
* jquery plugin to append an image after it is done preloading
* @author David Jeffries
* @date Oct 7, 2008
*/
var cachedImages = {}; // An object that holds and images that have already been loaded
$.fn.preloadAppend = function(options){
	// Passing an empty options.data grabs EVERY image on the screen... not good!
	if(options.data == ''){
		if(options.doneLoad){
			options.doneLoad();
		}
		return;
	}
	var images = $(options.data).find("img");
	if(images.length < 1){
		images = options.data;
	}
	var parent = $(this);//save this as a jquery object
	var size = $(images).length;
	
	var wrapper = options.wrap;
	
	var doneCount = 0;
	
	$(images).each(function(){
	
		var t = $(this); //save this as jquery for the onload function
		
		//t.css("visibility", "hidden");
	
		var src = t.attr("src");
		
		var i;
		
		// Find out if we have a cache hit
		if(cachedImages[src]){
			// If we do, use the stuff we got, fun the callback, then exit out.
			i = cachedImages[src];
			t.attr("src", i.src);
			parent.append(t);
			imgDone(t);
			return;
		}
		
		i = new Image();
		
		//set onload BEFORE setting the src (IE = retarded).
		i.onload = function(){
			//update with preloaded image
			t.attr("src", i.src);
			//console.log(t.wrap(wrapper));
			//we wrap the image with our optional wrapper.
			//t.wrap(wrapper);
			//console.log(wrapper);
			//var id = t.attr("id");
			
			parent.append(t);//.wrap(wrapper);
			
			//$("#temp" + r).wrap(wrapper);
			
			imgDone(t);
		}
	
		i.onerror = function(){
			imgDone(t);
		}
		
		i.src = src;
		
		cachedImages[i.src] = i;
		
	});
	
	/*
	* An image is done (either loaded, or error'd out)
	*/
	function imgDone(t){
		doneCount++;
		if(options.imageLoad){
			if(wrapper){
				t.wrap(wrapper);
			}
			options.imageLoad(t);
		}
		if(doneCount >= size && options.doneLoad){
			options.doneLoad();
		}
	}
}

/* 
* jquery plugin to force a large image to fit into a box
* @author David Jeffries
* @date October 7, 2008
*/
$.fn.imageBox = function(options){
	//console.log('imgboxing');		
	var defaults = {
		'mh': 150,
		'mw': 150,
		'box': true
	};
	$.extend(defaults, options);
	//console.log(defaults.mh);
	$(this).each(function(){
		
		var height = $(this).height();
		var width = $(this).width();
		//console.log($(this).attr("src"));
		var ratio = width / height;
		//console.log(height + "," + width);
		$(this).removeAttr("width");
		if(height > defaults.mh){
			//we need to scale porportionally to a target of mh (150) height
			$(this).height(defaults.mh);
			$(this).width(defaults.mw * ratio);
			//console.log(150 * ratio);
		}else if(width > defaults.mw){
			
			$(this).height(defaults.mh * ratio);
			$(this).width(defaults.mw);
			
		}else{
			$(this).attr("width", defaults.mw);
		}
		
		//add a margin to make it an actual box, if box is true
		if(defaults.box){
			var cw = $(this).width();//current width
			var ch = $(this).height();
			var widthdif = defaults.mw - cw; //find how much difference there is
			var heightdif = defaults.mh - ch;
			
			if(widthdif <= 0){
				widthdif = 0;
			}
			if(heightdif <= 0){
				heightdif = 0;
			}
			
			$(this).css({
				'margin-left': widthdif / 2,
				'margin-right': widthdif / 2,
				'margin-top': heightdif / 2,
				'margin-bottom': heightdif / 2
			});
		}
		
	});
}

function shareStyle(txtStyle){
	showPopup('<div id="tellfriend">\
		<form id="styleemailer" name="styleemailer">\
		<h1>Share your Sproost Style!</h1><br />\
		<b>Your Email Address</b><br />\
		<input style="width:275px; margin-bottom: 1em;" type="text" name="email" value="' + userEmail + '"><br />\
		<b>Your Friends\' Email Addresses</b><br />\
		<textarea style="width:275px; margin-bottom: 1em;" name="emails"></textarea>\
		<b>Subject</b><br />\
		<input style="width:275px; margin-bottom: 1em;" type="text" name="subject" value="My Sproost.com Style">\
		<b>Message</b><br />\
		<textarea style="width:275px;height:100px; margin-bottom: 1em;" name="message">Hey there - Sproost says my interior design style is:' + txtStyle + '</textarea>\
		<input type="submit" value="Send" class="submit"> <a id="cancel" href="#" onclick="hidePopup();">Cancel</a>\
		</form>\
		<div id="emailsent" style="margin-top: 10px; text-align: center;">Your message has been sent. Thanks for sharing your Sproost style with your friends!</div>\
	</div>', true, true);
	
	if(document.styleemailer.email.value.length > 0) {
    document.styleemailer.emails.focus();
  }else{
    document.styleemailer.email.focus();
  }
	$("#styleemailer").submit(function(){
		$("#cancel").remove();
		$.ajax({
		   type: "POST",
		   url: "/ajax/emailFriends",
		   data: $(this).serialize(),
		   success: function(data){
				$("#emailsent").css("display", "block");
				setTimeout('hidePopup()', 1500);
		   }
		 });
		 return false;
	});
}

function tellAFriend(){
	showPopup('<div id="tellfriend">\
		<form id="friendemailer">\
		<h1>Tell a Friend about Sproost</h1><br>\
		<p style="padding: 0 0 1em 0;"><b>Your Email</b><br>\
		'+userEmail+'</p>\
		<b>Your Friends\' Emails</b><br>\
		<textarea style="width:275px; margin-bottom: 1em;" name="emails"></textarea>\
		<b>Subject</b><br>\
		<input style="width:275px; margin-bottom: 1em;" type="text" name="subject" value="Check out Sproost.com">\
		<b>Message</b><br>\
		<textarea style="width:275px;height:100px; margin-bottom: 1em;" name="message">Thought you might like this site - you can figure out your home decorating style and see furniture in that style.</textarea>\
		<input type="submit" value="Send" class="submit"> <a id="cancel" href="#" onclick="hidePopup();">Cancel</a>\
		</form>\
		<div id="emailsent">Your message has been sent. Thanks for telling your friends about Sproost!</div>\
	</div>', true, true);
	
	$("#friendemailer").submit(function(){
		$("#cancel").remove();
		$.ajax({
		   type: "POST",
		   url: "/ajax/emailFriends",
		   data: $(this).serialize(),
		   success: function(data){
				$("#emailsent").css("display", "block");
				setTimeout('hidePopup()', 1500);
		   }
		 });
		 return false;
	});
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.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;
    }
};



