$(document).ready( function(){
	Layout.initBoxRound();
	$("input[type='checkbox']").custCheckBox();
	Layout.initNavigation();
	$(".bikeTeaser .details tbody tr").mouseover( function() {
		$(this).addClass("over");
	});
	$(".bikeTeaser .details tbody tr").mouseout( function() {
		$(this).removeClass("over");
	});
	$(".button").mouseover( function() {
		$(this).addClass("buttonOver");
	});
	$(".button").mouseout( function() {
		$(this).removeClass("buttonOver");
	});
	$(".buttonText").mouseover( function() {
		$(this).addClass("buttonTextOver");
	});
	$(".buttonText").mouseout( function() {
		$(this).removeClass("buttonTextOver");
	});
	$("#rfSearchButton").click( function() {
		RF.loadList("rfSearch", "bikelist");
		RF.showResults();
	});
	$("#searchContentShow").click( function() {
		RF.showSearch();
	});
	$("#newsmail").focus( function() {
        if($("#newsmail").val() == "Ihre E-Mail-Adresse"){
            $("#newsmail").val("");
        }
	});
	$("#newsmail").blur( function() {
        if(StringUtils.isEmpty($("#newsmail").val())){
		    $("#newsmail").val("Ihre E-Mail-Adresse");
        }
	});
	$("#searchContent select").change(function() {
		RF.updateSearch("rfSearch", "searchFields");
	});
    $("#addNewslistButton").click(function(){
        var theMailAddress = $("#newsmail").val();
        if(Validate.eMailAddress(theMailAddress)){
            Newsletter.addMail(theMailAddress, $("#chainrunnernews").attr("checked"));
            $("#newsmail").val("");
        } else {
            Status.show("Fehler", "Bitte geben Sie eine gültige E-Mail-Adresse an.");
        }
    });
	

	/*
	$("#right .target").hover( function() {
		jQuery(".underlineOnHoover", this).css("text-decoration","underline");
	}, function() {
		jQuery(".underlineOnHoover", this).css("text-decoration","none");
	});
	*/

	Layout.initIcons();

	//Layout.tableSetEven("details");
});

var Config = {}
Config.absoluteUrlPrefix = '/wheels/';

var Newsletter = {
    addMail: function(aMailAddress, aChainrunnerNews){
        if(Validate.eMailAddress(aMailAddress)){
            var theChainrunnerNews = BooleanUtils.toInt(aChainrunnerNews);
            Status.show("Hinzugefügt", "Die E-Mail-Adresse \"" + aMailAddress + "\" wurde zu unserem E-Mail-Verteiler hinzugefügt.");
        }
    }
}

var Layout = {
	/**
	 * @param[required]	tableCssName CSS-Class-Name of the table to modify
	 * @param[optional]	evenCssName CSS-Class which add to a even row, default is "even"
	 * @param[optional]	notOnlyBodyRows set true if you would like to use all rows, 
	 *					by default the rows into the tbody-tag only used
	 */
	tableSetEven: function(tableCssName, evenCssName, notOnlyBodyRows) {
		var bodyRowsTagName = " tbody";
		if(notOnlyBodyRows){
			bodyRowsTagName = "";
		}
		if(!evenCssName){
			evenCssName = "even";
		}
		$("table." + tableCssName + bodyRowsTagName + " tr").each(function(i,obj){
			if(i%2) {
				$(this).addClass(evenCssName);
			} else {
				$(this).removeClass(evenCssName);
			}
		});
	},
	/**
	 * @param[required]	id row-id to remove
	 */
	removeRow: function(id){
		$("#" + id).fadeOut("slow", function() {
			$("#" + id).remove();
		});
	},
	/**
	 * @param[optional]	cssPreClass
	 */
	initIcons: function(cssPreClass){
		if(!cssPreClass){
			cssPreClass = "";
		} else {
			cssPreClass = "." + cssPreClass + " ";
		}
		$(cssPreClass + ".icon16x16ScaleDown").click( function() {
			$(this).css("display","none");
			$(this).parent().children(".icon16x16ScaleUp").css("display","block");
			$(this).parent().parent().parent().children(".body").slideToggle("slow");
		});
		$(cssPreClass + ".icon16x16ScaleUp").click( function() {
			$(this).css("display","none");
			$(this).parent().children(".icon16x16ScaleDown").css("display","block");
			$(this).parent().parent().parent().children(".body").slideToggle("slow");
		});
		Notepad
		$(cssPreClass + ".icon16x16").mouseover( function() {
			$(this).addClass("icon16x16Over");
		});
		$(cssPreClass + ".icon16x16").mouseout( function() {
			$(this).removeClass("icon16x16Over");
		});
		Notepad.initIcons("bikeTeaser");
	},
	/**
	 * @param[optional]	cssPreClass
	 */
	initNavigation: function(){
		var url = document.location.href;
		var currentPage = url.substring(url.lastIndexOf("/"), url.length);
		$("#navigation a").each(function(index){
			var href = $(this).attr("href");
			var targetPage = href.substring(href.lastIndexOf("/"), href.length);
			if(currentPage == targetPage){
				$(this).addClass("active");
			}
		});
		$("#navigation a").hover( function() {
			$(this).addClass("over");
		}, function() {
			$(this).removeClass("over");
		});
	},
	initBoxRound: function() {
		$(".boxRound").wrapInner("<div><div><div><div></div></div></div></div>");
	}
}

var Form = {
	/**
	 * @param[required]	formId id of the form
	 */
	fieldsAsUrlParams: function(formId) {
		var paramString = "";
	    var $inputs = $('#' + formId + ' input, #' + formId + ' textarea, #' + formId + ' select');
	  	$inputs.each(function(i, el) {
		  	if(el.type == "checkbox" || el.type == "radio"){
			  	if(el.checked  == true){
			  		//alert(el.name + " - " + $(el).val());
			  		paramString = paramString + el.name + "=" + encodeURIComponent($(el).val()) + "&";
			  	}
		  	} else {
		  		paramString = paramString + el.name + "=" + encodeURIComponent($(el).val()) + "&";
		  	}
		});
	  	paramString = paramString.substring(0, (paramString.length -1));
	  	return paramString;
	}
}

var Paginate = {
	page: '1',
	hits: '10',
	lp: '1',
	sppc: '3',
	snpc: '3',
	getParamString: function(page, hits){
		var paramString =	"";
		var tmp = "page=" + Paginate.page;
		if(page){
			tmp = "page=" + page 
		}
		paramString = paramString + tmp;
		tmp = "&hits=" + Paginate.hits;
		if(hits){
			tmp = "&hits=" + hits 
		}
		paramString = paramString + tmp;
		
		paramString = paramString	+ "&lp=" + Paginate.lp 
									+ "&sppc=" + Paginate.sppc 
									+ "&snpc=" + Paginate.snpc;
		return paramString;
	}
}

var RF = {
	/**
	 * @param[required]	formId id of the form
	 * @param[required]	targetId id of the form
	 */
	loadList: function(formId, targetId, page, paramString) {
		$("#" + targetId).html("<div class=\"loader\" style=\"height:100px;\"></div>");
		var params = paramString;
        if(params == undefined || paramString == null || param.length <= 0)
            params = Form.fieldsAsUrlParams(formId);

		$("#" + targetId).load(Config.absoluteUrlPrefix + "templates/ajax/bikelist.jsp?" + Paginate.getParamString(page) + "&" + params, function(){
			Layout.initIcons("bikeTeaser");
		});
	},
	updateSearch: function(formId, targetId, loadAll) {

		var params = Form.fieldsAsUrlParams(formId);
		if(loadAll){
			params = "";
		}
		$("#" + targetId).load(Config.absoluteUrlPrefix + "templates/ajax/search.jsp?" + params, function(){
			$("#searchContent select").change(function() {
				RF.updateSearch("rfSearch", "searchFields");
			});
		});
	},
	showSearch: function(){
		RF.updateSearch("rfSearch", "searchFields", true);
		$("#searchContentShow").slideToggle("slow", function() {
			
		});
		$("#searchContent").slideToggle("slow");
	},
	showResults: function(){
		$("#searchContent").slideToggle("slow", function() {
			
		});
		$("#searchContentShow").slideToggle("slow");
	},
	scrollPage: function(page){
		
	}
}

var Status = {
	show: function(headline, text) {
	var notice = '<div class="notice">'
		  + '<div class="notice-body">' 
			  + '<img src="/wheels/img/purr/info.png" alt="" />'
			  + '<h3>' + headline + '</h3>'
			  + '<p>' + text + '</p>'
		  + '</div>'
		  + '<div class="notice-bottom">'
		  + '</div>'
	  + '</div>';
		$( notice ).purr({
			usingTransparentPNG: true
		});
	}
}

var Showcase = {
    toggle: function(bikeid, icon){
        $.get(Config.absoluteUrlPrefix + 'showcase?action=togglebike&bikeid=' + bikeid, function(){
            if($(icon).hasClass('icon16x16showcase-add')){
                $(icon).removeClass('icon16x16showcase-add');
                $(icon).addClass('icon16x16showcase-remove');
            } else {
                $(icon).removeClass('icon16x16showcase-remove');
                $(icon).addClass('icon16x16showcase-add');
            }
        });

    }
}

var Notepad = {
	add: function(bikeid) {
		if(bikeid){
			if(!$.cookie('notepad')){
				$.cookie('notepad', ';');
			}
			if($.cookie('notepad').indexOf(";" + bikeid + ";") != -1){
				return;
			}
			$.cookie('notepad', $.cookie('notepad') + bikeid + ";");
			Status.show("Hinzugefügt", "Das Fahrrad wurde zu Ihrem Merkzettel hinzugefügt.");
			Notepad.initIcons("bikeTeaser");
		}
	},
	remove: function(bikeid) {
		if($.cookie('notepad')){
			var ids = $.cookie('notepad');
			ids = ids.replace(bikeid + ";", "");
			$.cookie('notepad', ids);
			Notepad.initIcons("bikeTeaser");
			Status.show("Entfernt", "Das Fahrrad wurde von Ihrem Merkzettel entfernt.");
			$(".notepad #" + bikeid).fadeOut("slow");
		}
	},
	load: function(targetId){
		if($.cookie('notepad')){
			$("#" + targetId).html("<div class=\"loader\" style=\"height:100px;\"></div>");
			var params = "qf_id=" + $.cookie('notepad').substring(1, $.cookie('notepad').length -1);
			$("#" + targetId).load(Config.absoluteUrlPrefix + "templates/ajax/bikelist.jsp?" + params, function(){
				RF.showResults();
				Layout.initIcons();
			});
		}
	},
	isListed: function(bikeid) {
		if($.cookie("notepad")
				&& $.cookie("notepad").indexOf(";" + bikeid + ";") != -1){
			return true;
		}
		return false;
	},
	initIcons: function(containerCssClass) {
		$("." + containerCssClass).each(function(){
			if(Notepad.isListed($(this).attr("id"))){
				$(this).addClass("onNotepad");
			} else {
				$(this).removeClass("onNotepad");
			}
		});
	}
}

var Validate = {
    eMailAddress: function(aEmailAddress){
        var email = aEmailAddress;
        var AtPos = email.indexOf("@")
        var StopPos = email.lastIndexOf(".")
        var Message = undefined;

        if (email == "") {
        Message = "Not a valid Email address" + "\n"
        }

        if (AtPos == -1 || StopPos == -1) {
        Message = "Not a valid email address"
        }

        if (StopPos < AtPos) {
        Message = "Not a valid email address"
        }

        if (StopPos - AtPos == 1) {
        Message = "Not a valid email address"
        }
        
        var returnValue = false;
        if(StringUtils.isEmpty(Message))
            returnValue = true;

        return returnValue
    }
}

var StringUtils = {
    isEmpty: function(aString){
        if(aString == undefined
                || aString == null
                || aString.length <= 0
                ){
            return true;
        }
        return false;
    }
}

var BooleanUtils = {
    toInt: function(aBoolean){
        if(aBoolean)
            return 1;
        else
            return 0;
    }
}

/**
* 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;
   }
};
