// =========================================================

// scripts.js für rapidobject.com

// Datum: 2006-09-01
// Firma: Medienfreunde Hofmann & Baldes GbR
// Autor: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// =========================================================


/*
 * Klaus Hartl
 * jQuery Accordion
 */


$.fn.accordion = function(options) {
    // options
    var SLIDE_DOWN_SPEED = 'fast';
    var SLIDE_UP_SPEED = 'fast';
    var startClosed = options && options.startstat && options.startstat == 'closed';
    var on = options && options.on && (typeof options.on == 'number' && options.on > 0) ? options.on - 1 : 0;
    return this.each(function() {
        $(this).addClass('accordion'); // use to activate styling
        $(this).hover(function(){ $(this).addClass("hover"); },function(){ $(this).removeClass("hover"); });
        $(this).find('dd').hide();
        $(this).find('dt').click(function() {
            var current = $(this.parentNode).find('dd:visible');
            var next = $(this).next('dd');
            if (current[0] != next[0]) {
                //current.slideUp(SLIDE_UP_SPEED);
                current.fadeOut(SLIDE_UP_SPEED);
            } 
            if (next.is(':visible')) {
                //next.slideUp(SLIDE_UP_SPEED);
                //next.hide();
                next.fadeOut(SLIDE_UP_SPEED);
            } else {
                //next.slideDown(SLIDE_DOWN_SPEED);
                //next.show();
                next.fadeIn(SLIDE_DOWN_SPEED);
            }
        });
        if (!startClosed) {
            $(this).find('dd:eq(' + on + ')').slideDown(SLIDE_DOWN_SPEED);
        }
    });
};


/*
 * Jonathan Howard
 * jQuery Pause
 * version 0.2
 */

$.fn.pause = function(milli,type) {
	milli = milli || 1000;
	type = type || "fx";
	return this.queue(type,function(){
		var self = this;
		setTimeout(function(){
			$.dequeue(self);
		},milli);
	});
};

$.fn.clearQueue = $.fn.unpause = function(type) {
	return this.each(function(){
		type = type || "fx";
		if(this.queue && this.queue[type]) {
			this.queue[type].length = 0;
		}
	});
};

/*
 * http://www.dyve.net/jquery/?autohelp
 * jQuery Autohelp
 */
 
$.fn.autohelp = function(h,o) {
	//t = $(t); o = o || {};
	return this.each(function(){
  
	//t = $(t);
	var t = $(this).parents('ul').next(h);
	var tTitle = this.title;
	//o = o || {};

	var h;
	    
	$(this).focus(function() { h = t.html(); if (tTitle != '') { t.html('<p>'+tTitle+'</p>');};	})
	    .blur(function() { t.html(h); });
	    
	});
}

/* Button-Width */

$.fn.setTheWidth = function(o) {
	return this.each(function(){
		var factor = o || 1;
		var charLength = $(this).val().length;
		var theNewWidth = (charLength/2)+factor;
		$(this).width(theNewWidth+'em');
	}); 
};


/* Farbauswahl zeigen/verstecken */

function showHideColor() {
	if ($("#material").val() == "plastic") {
		$("#color").parent().show();
	} else {
		$("#color").parent().hide();
	};
};

// **** Preiskalkulator ****

function doPriceCalc () {
	
	var ufactor = parseFloat($("form#newobject input#userfactor").val());
	var pfactor = parseFloat($("form#newobject input#plasticfactor").val());
	
	var h = $("form#newobject input#height");
	var w = $("form#newobject input#width");
	var d = $("form#newobject input#depth");
	var v = $("form#newobject input#volume");
	var p = $("form#newobject input#price");
	var prov = $("form#newobject input#prov");
	var fp = $("form#newobject input#fullprice");
	var mat = $("form#newobject #material");
	
	if(mat.val() == 'plastic'){
		var factor = pfactor;
	}else{
		var factor = ufactor;
	}
	
	h.wert = h.val().replace(/,/, ".") || "0";
	w.wert = w.val().replace(/,/, ".") || "0";
	d.wert = d.val().replace(/,/, ".") || "0";
	v.wert = v.val().replace(/,/, ".") || "0";
	prov.wert = prov.val().replace(/,/, ".") || "0";
	
	if (isNaN(h.wert.replace(/\./, ""))) { h.addClass("error"); p.val(""); h.wert = "0"; fp.val("");} else { h.removeClass("error");};
	if (h.wert.replace(/\./, "") < 0) { h.wert *= -1; h.val(h.wert); };
	if (isNaN(w.wert.replace(/\./, ""))) { w.addClass("error"); p.val(""); w.wert = "0"; fp.val("");} else { w.removeClass("error");};
	if (w.wert.replace(/\./, "") < 0) { w.wert *= -1; w.val(w.wert); };
	if (isNaN(d.wert.replace(/\./, ""))) { d.addClass("error"); p.val(""); d.wert = "0"; fp.val("");} else { d.removeClass("error");};
	if (d.wert.replace(/\./, "") < 0) { d.wert *= -1; d.val(d.wert); };
	if (isNaN(v.wert.replace(/\./, ""))) { v.addClass("error"); p.val(""); v.wert = "0"; fp.val("");} else { v.removeClass("error");};
	if (v.wert.replace(/\./, "") < 0) { v.wert *= -1; v.val(v.wert); };
	if (isNaN(prov.wert.replace(/\./, ""))) { prov.addClass("error"); prov.wert = "0"; fp.val("");} else { prov.removeClass("error");};
	if (prov.wert.replace(/\./, "") < 0) { prov.wert *= -1; prov.val(prov.wert);};
	
	if (v.wert == "0") {
		var vol = (h.wert * w.wert * d.wert) / 1000;
	}else {
		var vol = v.wert;
	}
	
	var price = vol * factor;
	price = Math.round(price*100)/100; 
	price = price.toFixed(2);
	
	if (price == 0 || isNaN(price)) {
	}else{
		pricestring = price+" ";
		pricestring = pricestring.replace(/\./, ",");
		p.val(pricestring);
		if (isNaN(prov.wert)) {
		}else {
			var fprice = parseFloat(price) + parseFloat(prov.wert);
			fprice = fprice.toFixed(2);
			fpstring = fprice+" ";
			fpstring = fpstring.replace(/\./, ",");
			fp.val(fpstring);
		};
	};
};

function doPriceCalcLater () {
	
	var p = $("form#editobject input#base_price");
	var prov = $("form#editobject input#prov");
	var fp = $("form#editobject input#fullprice");
	
	p.wert = p.val().replace(/,/, ".") || "0";
	prov.wert = prov.val().replace(/,/, ".") || "0";
	
	if (isNaN(prov.wert.replace(/\./, ""))) { prov.addClass("error"); prov.wert = "0"; } else { prov.removeClass("error");};
	if (prov.wert.replace(/\./, "") < 0) { prov.wert *= -1; prov.val(prov.wert);};
	
	prov.wert = parseFloat(prov.wert);
	
	prov.wert = Math.round(prov.wert*100)/100; 
	
	var fp = parseFloat(p.wert) + parseFloat(prov.wert);
	fpstring = fp+" ";
	fpstring = fpstring.replace(/\./, ",");
	$("form#editobject input#fullprice").val(fpstring);

};



// **** Safari-Styles ****

function forABetterSafari(){
		$('head').append('<link rel="stylesheet" href="media/css/ro_safari.css"  type="text/css" media="all" />');
		
}

// **** Divs für Eckenabrundung einfügen ****

function doRound(){
	$('div.round').prepend('<div class="hd">'+ 
													'<div></div>'+
													'</div>')
								.append('<div class="ft">'+
												'<div></div>'+
												'</div>');    
};


// **** lastchild in Listen für IE ****

function doLastChild(elem){
	$(elem).each(function(){
      $(this).children(':last-child').addClass("lastchild");
    });
}




// **** li Hover-Hilfe für IE ****

function doActive(){
		$('ul#mainmenu li').hover(function(){ $(this).addClass("hover"); },function(){ $(this).removeClass("hover"); });
}


// **** externe Links standardkonform in neuem Fenster öffnen ****

function doRelTags() {
	$("a[@rel=external]").attr("target","_blank");
}

// **** Formularelemente für den IE mit Klassen belegen ****

function doFormClasses() {
	$("input[@type=text]").addClass("text");
	$("input[@type=password]").addClass("password");
	$("input[@type=submit]").addClass("submit");
	$("input[@type=reset]").addClass("reset");
	$("input[@type=radio]").addClass("radio");
	$("input[@type=checkbox]").addClass("checkbox");
	$("input[@type=file]").addClass("file");
	$("input[@readonly]").addClass("readonly");
}

// **** Erweiterte Suche ****

function doSearchMore() {
	$('form div#sidesearchmore').hide().before('<small><a href="#sidesearchmore" onfocus="blur();" onclick="$(\'form div#sidesearchmore\').slideToggle(\'fast\');return false;" >Details</a></small>');
}


// **** Rating-System in der Galerie transparent machen****

function doTransRate(){
	$('ul.gallery li div.rate').fadeTo(1, 0.3).hover(function(){ $(this).fadeTo("normal", 1); },function(){ $(this).fadeTo("slow", 0.3); });
}

// **** Quicktime initialisieren****

function writeQT (file){
	var roModel = new QTObject(file, "qtpreview", "320", "320");
	roModel.addParam("controller", "false");
	roModel.addParam("kioskmode", "true");
	roModel.addParam("bgcolor", "#F2F2F2");
	roModel.addParam("scale", "aspect");
	roModel.write('qtmov');
	
	$('div.moddet div.col').not(".first").append('<div id="qthelpsmall" style="margin-top: 2em; height: 80px; overflow: hidden; background: transparent url(http://rapidobject.com/media/img/qthelp_small.png) 0 0 no-repeat;">&nbsp;</div>');
	$('div#qtmov').hover(function(){ $('div#qthelpsmall').fadeTo("normal", 1.0); },function(){ $('div#qthelpsmall').fadeTo("slow", 0); });
}

function doQt(){
	// Hilfeeinblendung
	$('div#qt div#qtmov a span#qthelp').fadeTo("slow", 0);
	$('div#qt div#qtmov a').hover(function(){ $('div#qt div#qtmov a span#qthelp').fadeTo("normal", .7); },function(){ $('div#qt div#qtmov a span#qthelp').fadeTo("slow", 0); });
	
	// onClick einbinden
	$('div#qt div#qtmov a').click(function(){ 
			writeQT(this.href);
			return false;
		});
}


// **** BETA ****

function doBeta() {
	$('body').prepend('<div style="position: absolute; z-index: 100; top: 0; left: 0; width: 100px; height: 100px; overflow: hidden; background: transparent url(http://rapidobject.com/media/img/beta.png) 0 0 no-repeat;">&nbsp;</div>');
}

// **** Colorpicker ****

function initPicker(){ 
	//$('#picker').hide();
	
	if (document.getElementById('picker')) {
		var f = $.farbtastic('#picker');
	  var p = $('#picker');
	  var selected;
	  $('.colorwell')
	      .each(function () { f.linkTo(this); })
	      .focus(function() {
	        if (selected) {
	          $(selected).removeClass('colorwell-selected');
	          //p.hide();
	        }
	        f.linkTo(this);
	        //p.show();
	        $(selected = this).addClass('colorwell-selected');
	      })
				.blur(function() {
	        if (selected) {
	          $(selected).removeClass('colorwell-selected');
	          //p.hide();
	        }
	  });
	};
	
};


function showPrice(incent){
	euro = incent/100;
	euro = euro.toFixed(2)+'';
	return euro.split(".").join(",")+' €';
}
// **** shipping cost update on checkout form ****
function setShippingCosts(){
	var newshipcosts = allshipcosts[$('form#checkoutform #shipping_country').val()];
	var newtotal = currentsubtotal+newshipcosts;
	//alert('Updating Shipping Costs: '+newshipcosts);
	// write newshipcosts to page
	$('#currentshippingcostarea').html(showPrice(newshipcosts));
	// write newtotal to page
	$('#currenttotalarea').html(showPrice(newtotal));
}

// **** durch News wechseln ****
/*
 * jQuery Cycle Plugin for light-weight slideshows
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 *
 * @author: M. Alsup
 * @version: 1.0.1 (7/15/2007)
 * @requires jQuery v1.1.2 or later
 *
 * Based on the work of:
 *  1) Matt Oakes (http://portfolio.gizone.co.uk/applications/slideshow/)
 *  2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
 */
(function($) {

$.fn.cycle = function(options) {
    return this.each(function() {
        if (options && options == 'stop') {
            if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
            this.cycleTimeout = 0;
            return;
        }
        var $this = $(this), els = $this.children();
        if (els.length < 2) return; // don't bother

        var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.meta ? $this.data() : {});

        // allow shorthand overrides of width, height and timeout
        var cls = this.className;
        var w = parseInt((cls.match(/w:(\d+)/)||[])[1]) || opts.width
        var h = parseInt((cls.match(/h:(\d+)/)||[])[1]) || opts.height;
        opts.timeout = parseInt((cls.match(/t:(\d+)/)||[])[1]) || opts.timeout;

        // make sure the timeout and speed settings are sane
        if (opts.speed.constructor == String)
            opts.speed = {slow: 600, fast: 200}[opts.speed] || 400;
        while((opts.timeout - opts.speed) < 250)
            opts.timeout += opts.speed;

        if ($this.css('position') == 'static') $this.css('position', 'relative');
        if (w) $this.width(w);
        if (h && h != 'auto') $this.height(h);

        var $els = $(els).each(function(i){$(this).css('z-index', els.length-i);}).css('position','absolute').hide();
        if (opts.fit && w) $els.width(w);
        if (opts.fit && h && h != 'auto') $els.height(h);
        $(els[0]).show();

        if (opts.pause)
            $this.hover(function(){opts.paused=1;}, function(){opts.paused=0;});

        opts.current = opts.random ? (Math.floor(Math.random() * (els.length-1)))+1 : 1;
        opts.last = 0;
        this.cycleTimeout = setTimeout(function(){$.fn.cycle.go(els, opts)}, opts.timeout);
    });
};

$.fn.cycle.go = function (els, opts) {
    if (els[0].parentNode.cycleTimeout === 0) return;
    if (!opts.paused) {
        if (opts.fade) {
            $.fn.cycle.fadeToggle(els[opts.last], opts.speed);
            $.fn.cycle.fadeToggle(els[opts.current], opts.speed);
        }
        else {
            //$(els[opts.last]).slideUp(opts.speed);
            //$(els[opts.current]).slideDown(opts.speed);
            $(els[opts.last]).hide();
            $(els[opts.current]).show();
        }
        

        if (opts.random) {
            opts.last = opts.current;
            while (opts.current == opts.last)
                opts.current = Math.floor(Math.random() * els.length);
        }
        else { // sequence
            var roll = (opts.current + 1) == els.length;
            opts.current = roll ? 0 : opts.current+1;
            opts.last    = roll ? els.length-1 : opts.current-1;
        }
    }
    setTimeout(function() { $.fn.cycle.go(els, opts) }, opts.timeout);
};

// this allows more flexibility than the core fade methods
$.fn.cycle.fadeToggle = function(el, speed){
   var $el = $(el);
   var to = $el.is(':visible') && $el.css('opacity') > 0 ? 0 : 1;
   if (to) $el.css('opacity',0).show();
   $el.fadeTo(speed, to, function() {
       to ? $(this).show() : $(this).hide();
   });
};

$.fn.cycle.defaults = {
    height:  'auto',   // container height
    fade:     1,       // true for fade, false for slide
    speed:    600,     // any valid fx speed value
    timeout:  5000,    // ms duration for each slide
    random:   0,       // true for random, false for sequence
    fit:      0,       // force slides to fit container
    pause:    1        // true to enable "pause on hover"
};

})(jQuery);


// **** führt Funktionen aus, sobald DOM verfügbar ist ****

$(document).ready(
	function(){
		doRound();
		doActive();
		doRelTags();
		$('ul#mainmenu li:eq(3) a').addClass('new_star_holder').append('<div class="new_star">&nbsp;</div>');
		if (jQuery.browser.safari) {
			forABetterSafari();
		};
		doTransRate();
		if (jQuery.browser.msie) {
			doFormClasses();
			$('table tr').hover(function(){ $(this).addClass("hover"); },function(){ $(this).removeClass("hover"); });
			$("input[@type=submit]").not(".input.next, input.refresh, input.back, input.delete, input.save, input.paypal").setTheWidth();
			$("input.next, input.refresh, input.delete, input.save").setTheWidth(1.5);
			$("input.back, input.paypal").setTheWidth(2.1);
		};
		if (jQuery.browser.msie || jQuery.browser.opera) {
			doLastChild('ul.imglist, dl.separated, ul.submenu');
		};
		
		$('table tr:even').addClass('even');
		doSearchMore();
		//doBeta();
		if (document.getElementById('qtmov')) {
			doQt();
		};
		$('.datacollect input, .datacollect select, .datacollect textarea').not(".datacollect input.colorwell").autohelp('div.formhelp');
		$('form#newobject input#height, form#newobject input#width, form#newobject input#depth, form#newobject input#volume, form#newobject input#prov, form#newobject #material').change(doPriceCalc);
		$('form#checkoutform #shipping_country').change(setShippingCosts);
		$('form#editobject input#prov').change(doPriceCalcLater);
		if ($.fn.highlightFade) {
			$('.message').highlightFade({speed:1500});
			$('.alert').highlightFade({color:'rgb(255, 51, 0)', speed:1500});
		};
		//$('input.back, a.back').click(function(){ history.back(); return false; });
		$('dl.faq').accordion({startstat: "closed"});
		$('div#errorlayer, div#messagelayer').slideDown().animate({opacity: 1.0}, 2000).fadeOut('fast', function() {$(this).remove();});
		$('div#errorlayer, div#messagelayer').click( function() {
			$('div#errorlayer, div#messagelayer').css("top", "-10000px");
		});
		//	TB_init();
		/*
		$('.galmore .trigger').click( function() {
			this.blur();
			$(this).parents('.galmore').find('.pane').slideToggle('fast');
			return false;
		});
		*/
		if (document.getElementById('material')) {
			showHideColor();
			$("#material").change( showHideColor );
		};
		
		if ($.fn.farbtastic) {
			initPicker();
		};
		if ($.fn.cycle) {
			if (jQuery.browser.msie) {
				$('.news').cycle({fade:0});
			}else {
				$('.news').cycle();
			};
			
			$('ul.fade_gallery').cycle({
		    pause:    0
			});
		};
});


