//base JS file Panache Superbra

$(document).ready(function () {
    //do stuff here

    /* all sorts of variables */
    var $document = $(document);
    var $homeSlideshow = $('#home-slideshow');
    var $sectionSlideshow = $('#section-slideshow');
    var $sectionCollection = $('#section-collection');
    var $sectionProduct = $('#section-page');
    var homeSlides = [];
    //var homeLinks = [];
    var currentSlide = 0;
    var scrollOffset = 0;
    var currentScroll = 0;

    var homeInterval;
    var homeSlideTransitionTime = 2000;
    var homeSlideIntervalTime = 8000;

    var sectionInterval;
    var sectionSlideTransitionTime = 1500;
    var sectionSlideIntervalTime = 9000;

    /* homepage functions */
    if ($homeSlideshow.length > 0) {
        $(window).bind('resize', resizeHome);
        resizeHome();
        initHomeSlideshow();
		$('.open-close-button').bind('click', toggleSmallNavigation).trigger('click');
    }
    function initHomeSlideshow() {
        $homeSlideshow.find('a.img').each(function (index, el) {
            $(el).hide();
            homeSlides.push($(el));
            $linkEl = $homeSlideshow.find('a.link').eq(index);
 			$linkEl.hide();
 			//homeLinks.push($linkEl);
        });
        homeSlides[0].fadeIn();
        //homeLinks[0].fadeIn();
        if (homeSlides.length > 1) {
            homeInterval = setTimeout(doHomeSlideshow, homeSlideIntervalTime);
        }
    }
    function doHomeSlideshow() {
        homeSlides[currentSlide].fadeOut(homeSlideTransitionTime);
        if (currentSlide + 1 < homeSlides.length) {
            currentSlide++;
        } else {
            currentSlide = 0;
        }
        homeSlides[currentSlide].fadeIn(homeSlideTransitionTime);
        //homeLinks[currentSlide].fadeIn(homeSlideTransitionTime);
        homeInterval = setTimeout(doHomeSlideshow, homeSlideIntervalTime);
    }
    function resizeHome() {
        var $document = $(document);
        //document size
        var $window = $(window);
        $homeSlideshow.css('height', ($window.height() - 35) + 'px').find('img').each(function (index, el) {
            var $el = $(el);
            //get current width
            var elWidth = $el.width();
            //get current height
            var elHeight = $el.height();
            //get ratio
            var ratio = elWidth / elHeight;
            //resize to fit
            var w, h;
            var offsetx = 0;
            h = $window.height();
            w = h * ratio;
            if (w < $window.width()) {
                w = $window.width();
                h = w / ratio;
            }
            if (w > $window.width()) {
                offsetx = (($window.width() - w) / 2);
            }
            $el.attr('width', w).attr('height', h).parent().css('left', offsetx + 'px');

        })
    }

    /* section functions */
    if ($sectionSlideshow.length > 0) {
        $(window).bind('resize', resizeSection);
        resizeSection();
        $('.open-close-button').bind('click', toggleSmallNavigation).trigger('click');
        //loaded images..
        //load images from the hidden fields
        turnInputsToCollectionImages(0);
        //scrollabr
        $('#handle').bind('mousedown', doSectionScroll);
        if (Modernizr.touch) {
            $('#handle').bind('touchstart', doSectionTouchScroll);
        }
        
    }
   
    function doSectionScroll(e)
    {
    	e.preventDefault();
        scrollOffset = e.clientX - parseInt($('#handle').css('left'));
        $(document).bind('mousemove', doSectionScrolling);
    }
    function doSectionTouchScroll(e)
    {
    	e.preventDefault();
        scrollOffset = e.pageX - parseInt($('#handle').css('left'));
        $(document).bind('touchmove', doSectionTouchScrolling);
    }
    function doSectionScrolling(e)
    {
    	e.preventDefault();
        val = (e.clientX - scrollOffset);
        if (val + $('#handle').width() > $(window).width()) {
            val = $(window).width() - $('#handle').width();
        } else if (val < 0) {
            val = 0;
        }

        //change val into a percent
        valPercent = (val / ($(window).width() - $('#handle').width()));
        scrollContent($('#section-slideshow'), $('#section-mask'), valPercent); //content, content container, percentage to scroll, optional value for fixed width
        $('#handle').css('left', val + 'px');
        $(document).bind('mouseup', doSectionEndScroll);
    }
    function doSectionTouchScrolling(e)
    {
		e.preventDefault();
        val = (e.pageX - scrollOffset);
        if (val + $('#handle').width() > $(window).width()) {
            val = $(window).width() - $('#handle').width();
        } else if (val < 0) {
            val = 0;
        }

        //change val into a percent
        valPercent = (val / ($(window).width() - $('#handle').width()));
        scrollContent($('#section-slideshow'), $('#section-mask'), valPercent); //content, content container, percentage to scroll, optional value for fixed width
        $('#handle').css('left', val + 'px');
        $(document).bind('touchend', doSelectionTouchEndScroll);
    }
    function doSectionTouchEndScroll(e) {
        e.preventDefault();
        $(document).unbind('touchmove', doSectionTouchScrolling);
    }
    function doSectionEndScroll(e) {
        e.preventDefault();
        $(document).unbind('mousemove', doSectionScrolling);
    }
    
    function resizeSection()
    {
    	var wdth = 0;
    	var hght = $(window).height() - 10; //not sure why it needs 10 taking away — but it does...
    	$('.section-slideshow-item').find('img').each(function(index, el){
    		var $el = $(el);
    		var ratio = $el.attr('width') / $el.attr('height');
    		$el.height(hght).width(hght*ratio);
    		$el.parent().height($el.height()).width($el.width());
    		wdth+= $el.width();	
    	})
    	$('#section-slideshow').width(wdth);
    	if (wdth > $(window).width()){
    		//show scrollbar
    		if ($('.scroll-holder').css('display') != 'block'){
    			showScrollbar();
    		}
    	} else {
    		hideScrollbar();
    	}
    	//scroll to the correct place (ie: keep handle at same percentage, but move the content to that percent, this should keep it in the same place...
    	//although handle percentage will change so we should keep that in a variable and call that rather than the actual position.
    	//change the size of the handle to reflect content vs window size too.
    	var handleScale = $('#section-slideshow').width() / $(window).width();
    	$('#handle').width($(window).width() / handleScale);
    	scrollContent($('#section-slideshow'), $('#section-mask'), currentScroll); //content, content container, percentage to scroll, optional value for fixed width
    	var handleValue = ($('#section-collection-scroll').width() - $('#handle').width())*currentScroll;
    	$('#handle').css('left', handleValue+'px');
       
    }
    function initSectionImages(event)
    {
    	var $this = $(this);
    	if ($this.width() != 0){
    		$this.attr('width', $this.width());
    		$this.attr('height', $this.height());
    	}
    	$this.fadeIn(500, function(){
   			if ($('.lifestyleImage').length > 0){
   				turnInputsToCollectionImages(0);
	    	}
    	});
    	resizeSection();
    }
    function turnInputsToCollectionImages(index)
    {
    	var $imgInput = $('.lifestyleImage').eq(0);
    	var $linkInput = $('.lifestyleImageLink').eq(0);
    	var src = $imgInput.attr('value');
    	$imgInput.removeClass('to-load');
    	var href = $linkInput.attr('value');
    	var link = document.createElement('a');
    		link.className = 'section-slideshow-item';
    		link.href = href;
    	var img = new Image();
    		img.src = src;
    		link.appendChild(img);
    	$('#section-slideshow').append(link);
    	$imgInput.remove();
    	$linkInput.remove();
    	$(img).hide();
    	$(img).imagesLoaded(initSectionImages);
    }
    function toggleSmallNavigation() {
        $bar = $('#section-info-bar');
        if ($bar.hasClass('open')) {
            //it's open, close it.
            //animate to minus the width of the element, excluding the button
            num = $bar.width() - 25;
            $bar.removeClass('open').addClass('closed').animate({'left': -num+'px'}, 500);
        } else {
            //it's closed, open it.
            $bar.removeClass('closed').addClass('open').animate({'left': '0px'}, 500);
        }
    }
    /* Sports Page Featured Functions */
    
    var currentSportsPage = 0;
    var totalSportsPage = 0;
    if ($('.sport-slider-item').length > 0) {
    	totalSportsPage = $('.sport-slider-item').length;
        //$('.open-close-button').bind('click', toggleSmallNavigation).trigger('click');
    	//$('#handle').bind('mousedown', doSportScroll);
        //if (Modernizr.touch) {
          //  $('#handle').bind('touchstart', doSportTouchScroll);
        //}
        $(window).bind('resize', resizeSportSection);
        resizeSportSection();
        //$('#sport-inner-navigation a').bind('click', jumpToSportSection);
        $('#sports-left-btn').bind('click', prevSportsPage);
        $('#sports-right-btn').bind('click', nextSportsPage);
        $('.sport-slider-item').find('.image img').imagesLoaded(resizeSportSection);
        checkSportsPagination();
    }
    function prevSportsPage()
    {
    	if (!$(this).hasClass('disabled')){
    		currentSportsPage--;
   		} else {
		   	currentSportsPage = totalSportsPage-1;	    	
    	}
    	var jumpToIndex = currentSportsPage;
		var jumpToOffset = (($(window).width()*jumpToIndex)*-1);
		$('#sport-slider').stop().animate({'left': jumpToOffset+'px'}, 750)

    	checkSportsPagination();
    }
    function nextSportsPage()
    {
    	if (!$(this).hasClass('disabled')){
    		currentSportsPage++;
    	} else {
			//jump to beginning
			currentSportsPage = 0;
		}
		var jumpToIndex = currentSportsPage;
		var jumpToOffset = (($(window).width()*jumpToIndex)*-1);
		$('#sport-slider').stop().animate({'left': jumpToOffset+'px'}, 750)
		checkSportsPagination();
    }
    function checkSportsPagination()
    {
    	var $prev = $('#sports-left-btn');
    	var $next = $('#sports-right-btn')
    	if (currentSportsPage == 0){
    		//disable previous
    		$prev.addClass('disabled');
    		$next.removeClass('disabled');
    	} else if(currentSportsPage == totalSportsPage-1) {
    		//disable next
    		$next.addClass('disabled');
    		$prev.removeClass('disabled');
    	} else {
    		//enable both
    		$prev.removeClass('disabled');
    		$next.removeClass('disabled');
    	}
    }
	function jumpToSportSection()
	{
		var jumpToIndex = $(this).parent().index();
		var jumpToOffset = (($(window).width()*jumpToIndex)*-1);
		//$('#sport-slider').stop().animate({'left': jumpToOffset+'px'}, 750);
		var currentScrollIndex = (jumpToIndex/($('.sport-slider-item').length-1));
		var handleValue = ($('#section-collection-scroll').width() - $('#handle').width())*currentScrollIndex;
    	$('#handle').stop().animate({'left': handleValue+'px'}, 750);
	}
    function resizeSportSection()
    {
    	var wdth = $(window).width() * $('.sport-slider-item').length;
    	$('.sport-slider-item').width($(window).width()).height($(window).height()).find('.container').each(function(index, el){
    		var $this = $(this);
    		var $text = $this.find('.text');
    		var $image = $this.find('.image');
    		//if the text is smaller than the image
    		if ($text.height() < $image.height()){
    			//add some padding to the top of the text
    			var newVal = ($image.height() - $text.height())/2;
    			$text.css('padding-top', newVal+'px')
    		}
    		//then centre the container
    		var newTopVal = ($(window).height() - $this.height())/2;
    		$this.css('margin-top', newTopVal+'px')
    	})
    	
    	var jumpToIndex = currentSportsPage;
		var jumpToOffset = (($(window).width()*jumpToIndex)*-1);
    	$('#sport-slider').css('left', jumpToOffset+'px');
    }
    
    function doSportScroll(e)
    {
    	e.preventDefault();
        scrollOffset = e.clientX - parseInt($('#handle').css('left'));
        $(document).bind('mousemove', doSportScrolling);
    }
    function doSportTouchScroll(e)
    {
    	e.preventDefault();
        scrollOffset = e.pageX - parseInt($('#handle').css('left'));
        $(document).bind('touchmove', doSportTouchScrolling);
    }
    function doSportScrolling(e)
    {
    	e.preventDefault();
        val = (e.clientX - scrollOffset);
        if (val + $('#handle').width() > $(window).width()) {
            val = $(window).width() - $('#handle').width();
        } else if (val < 0) {
            val = 0;
        }

        //change val into a percent
        valPercent = (val / ($(window).width() - $('#handle').width()));
        scrollContent($('#sport-slider'), $('#sports-slider-mask'), valPercent); //content, content container, percentage to scroll, optional value for fixed width
        $('#handle').css('left', val + 'px');
        $(document).bind('mouseup', doSportEndScroll);
    }
    function doSportTouchScrolling(e)
    {
		e.preventDefault();
        val = (e.pageX - scrollOffset);
        if (val + $('#handle').width() > $(window).width()) {
            val = $(window).width() - $('#handle').width();
        } else if (val < 0) {
            val = 0;
        }

        //change val into a percent
        valPercent = (val / ($(window).width() - $('#handle').width()));
        scrollContent($('#sport-slider'), $('#sports-slider-mask'), valPercent); //content, content container, percentage to scroll, optional value for fixed width
        $('#handle').css('left', val + 'px');
        $(document).bind('touchend', doSportTouchEndScroll);
    }
    function doSportTouchEndScroll(e) {
        e.preventDefault();
        $(document).unbind('touchmove', doSportTouchScrolling);
    }
    function doSportEndScroll(e) {
        e.preventDefault();
        $(document).unbind('mousemove', doSportScrolling);
    }
    
    /* Scrollbar functions */
    function scrollContent(content, container, percent, optionalWidth) {
        if (optionalWidth) {
            contentWidth = optionalWidth[0];
        } else {
            contentWidth = $(content).width();
        }
        currentScroll = percent;
        //get the width of the content, 
        //get the width of the container
        containerWidth = $(container).width();
        //get the difference, this is how much is scrolls by
        contentOffsetMax = contentWidth - containerWidth;
        //times the difference by the percentage multiplier
        contentOffset = contentOffsetMax * percent;
        //set the css to minus that number ie: offset off the left of the page
        $(content).css('left', (contentOffset * -1) + 'px');
    }
    function showScrollbar() {
        $('.scroll-holder').show();
        currentScroll = 0;
        $('#handle').css('left', '0px');
    }
    function hideScrollbar() {
        $('.scroll-holder').hide();
    }
    /* New Collection Fuctions... */
    currentCollectionPage = 0;
    $collectionPages = $('.collection-page-item');
    $pages = $('.collection-page');
    totalCollectionPages = Math.floor($collectionPages.length/8); 
    $nextBtn = $('#collection-right-btn');
    $prevBtn = $('#collection-left-btn');
    collectionAnimating = false;
    $collectionHolder = $('#collection-inner-slide');
    if (totalCollectionPages > 0){
    	//init the infinite scroller
    	collectionScrollInit();
    } else {
   		$nextBtn.hide();
   		$prevBtn.hide();
    }
    function collectionScrollInit()
    {
    	//detach the last page and bring it to the start
		var $firstpage = $pages.last().detach();
		$pages.parent().prepend($firstpage);
    	//jump to next page
    	$collectionHolder.css('left', '-960px');
    	//if there is more than one page
    	//assign the event listeners
    	$nextBtn.bind('click', nextCollectionLoop);
	    $prevBtn.bind('click', prevCollectionLoop);
    }
    function nextCollectionLoop()
    {
		if (!collectionAnimating){
			//update pages..
			$pages = $('.collection-page');
			//set animation flag
			collectionAnimating = true;
			//duplicate first and append to end.
			var $firstpage = $pages.eq(0).clone();
			$pages.parent().append($firstpage);
			//animate the strip left -960px;
			var currentLeft = parseInt($collectionHolder.css('left'));
			var newLeft = currentLeft - 960;
			$collectionHolder.animate({'left': newLeft+'px'}, 750, function(){
				//when done animating remove first element
				$pages.eq(0).remove();
				//add that 960 back...
				$collectionHolder.css('left', currentLeft+'px');
				//set animation flag
				collectionAnimating = false;
			})
			//
		}    
    }
    function prevCollectionLoop()
    {
    	if (!collectionAnimating){
			//update pages..
			$pages = $('.collection-page');
			//set animation flag
			collectionAnimating = true;
			//duplicate last and prepend
			var $lastpage = $pages.last().clone();
			$pages.parent().prepend($lastpage);
			//immediately take 960
			//animate the strip left +960px;
			var currentLeft = parseInt($collectionHolder.css('left'));
			var newLeft = currentLeft - 960;
			$collectionHolder.css('left', newLeft+'px').animate({'left': currentLeft+'px'}, 750, function(){
				//when done animating remove first element
				$pages.last().remove();
				//set animation flag
				collectionAnimating = false;
			})
			
		}  
    }
    
    /* Section Product Functions */
    if ($sectionProduct.length > 0) {
        resizeProduct(false);
        $(window).bind('resize', resizeProduct);
        //$('#handle').bind('mousedown', doProductScroll);
        //is a touch enabled device?
        //if (Modernizr.touch) {
        //    $('#handle').bind('touchstart', doProductTouchScroll);
        //}
        //$('.section-page-images-inner-item a').bind('click', openProductOverlay);
        $('#section-page-overlay-close').bind('click', closeProductOverlay);
        $('#section-page-hitarea').bind('click', closeProductOverlay);
        $('.star').bind('click', changeRating);
    }

    function changeRating() {
        $this = $(this);
        num = $this.attr('class').substr(0, 1); /* Make sure the first class name is 1, 2, 3, 4, or 5. */
        $this.parent().data("rating", Number(num)); //store the selected rating.
        $this.parent().children('a.star').each(function (index, el) {
            $el = $(el);
            if (index < num) {
                $el.removeClass('empty').addClass('full');
            } else {
                $el.removeClass('full').addClass('empty');
            }
        })
    }    
    function openProductOverlay() {
        thisLink = this;
        $this = $(this);
        $('#section-page-overlay').fadeIn();
    }
    function changeProductOverlay() {
        thisLink = this;
        $this = $(this);
    }
    function closeProductOverlay() {
        $('#section-page-overlay').fadeOut();
    }



    function resizeProduct(ignoreScroller) {
        $window = $(window);
        $sectionPageImagesItems = $('.section-page-images-inner-item');
        imagesWidth = $sectionPageImagesItems.width() * $sectionPageImagesItems.length;
        $sectionPageImages = $('#section-page-images');
        $innerText = $('#section-page-overlay-inner-information-reviews');
        $innerText.css('height', ($window.height() - $innerText.offset().top - 36) + 'px');
    }
    function resizeProductCall() {
        resizeProduct(true);
    }
    function doProductTouchScroll(e) {
        e.preventDefault();
        scrollOffset = e.pageX - parseInt($('#handle').css('left'));
        $(document).bind('touchmove', doProductTouchScrolling);
    }

    function doProductScroll(e) {
        e.preventDefault();
        scrollOffset = e.clientX - parseInt($('#handle').css('left'));
        $(document).bind('mousemove', doProductScrolling);
    }
    function doProductTouchScrolling(e) {
        e.preventDefault();
        val = (e.pageX - scrollOffset);
        if (val + $('#handle').width() > $(window).width()) {
            val = $(window).width() - $('#handle').width();
        } else if (val < 0) {
            val = 0;
        }
        //optional content width for fixed divs, ie: 10000px
        $sectionPageImagesItems = $('.section-page-images-inner-item');
        imagesWidth = $sectionPageImagesItems.width() * $sectionPageImagesItems.length;

        //change val into a percent
        valPercent = (val / ($(window).width() - $('#handle').width()));
        scrollContent($('#section-page-images-inner'), $('#section-page-images'), valPercent, [imagesWidth]); //content, content container, percentage to scroll, optional value for fixed width stuff
        $('#handle').css('left', val + 'px');
        $(document).bind('touchend', doProductTouchEndScroll);
    }
    function doProductScrolling(e) {
        e.preventDefault();
        val = (e.clientX - scrollOffset);
        if (val + $('#handle').width() > $(window).width()) {
            val = $(window).width() - $('#handle').width();
        } else if (val < 0) {
            val = 0;
        }
        //optional content width for fixed divs, ie: 10000px
        $sectionPageImagesItems = $('.section-page-images-inner-item');
        imagesWidth = $sectionPageImagesItems.width() * $sectionPageImagesItems.length;

        //change val into a percent
        valPercent = (val / ($(window).width() - $('#handle').width()));
        scrollContent($('#section-page-images-inner'), $('#section-page-images'), valPercent, [imagesWidth]); //content, content container, percentage to scroll, optional value for fixed width stuff
        $('#handle').css('left', val + 'px');
        $(document).bind('mouseup', doProductEndScroll);
    }
    function doProductTouchEndScroll(e) {
        e.preventDefault();
        $(document).unbind('touchmove', doProductTouchScrolling);
    }

    function doProductEndScroll(e) {
        $(document).unbind('mousemove', doProductScrolling);
    }
    /* Brand drop-down */
    $('.drop-down-brands .list a').bind('click', changeDropDown);
    function changeDropDown()
    {
    	$this = $(this);
    	newText = $this.text();
    	$label = $this.parent().parent().siblings('.selected');
    	$label.text(newText);
    	$label.attr('rel', $this.attr('rel'));
    }
    /* Advice page functions */
    $('.advice-button').bind('click', changeAdvice);
    function changeAdvice()
    {
    	$btn = $(this);
    	$otherBtns = $btn.siblings('.advice-button');
    	newContentId = $btn.attr('rel');
    	$newContent = $('#'+newContentId);
    	$otherContent = $newContent.siblings('.content');
    	
    	if ($btn.hasClass('inactive')){
	    	$btn.removeClass('inactive').addClass('active');
	    	$otherBtns.removeClass('active').addClass('inactive')
	    	$newContent.removeClass('inactive').addClass('active');
	    	$otherContent.removeClass('active').addClass('inactive')
    	}
    }
});
$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load.imgloaded',function(){
      if (--len <= 0 && this.src !== blank){ 
        elems.unbind('load.imgloaded');
        callback.call(elems,this); 
      }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }  
  }); 

  return this;
};
var $gluubF = {};


//jQuery extentsion to create the modals used by this site and all full sizable.  Its more complex than I had antisipated !!!
jQuery.fn.modal = function () {

    var modalElement = this[0];

    if (modalElement.modal)
        return modalElement.modal;

    var modalObject = new $gluubF.modal(modalElement, arguments[0] || {});

    return $(modalElement);
};

$gluubF.modal = function (modalElement, args) {
    var width = args.width;
    var height = args.height;
    var closeClickedCallback = args.closeClickedCallback;
    var showClose = args.showClose || true;
    var dims = { tl: { w: 31, h: 31 }, tr: { w: 31, h: 31 }, bl: { w: 31, h: 31 }, br: { w: 31, h: 31 }, t: { h: 15 }, b: { h: 23 }, l: { w: 16 }, r: { w: 22 }, inPad: { t: 15, r: 22, b: 23, l: 16} };
    var newModal = $('<div class="modal_greyOut"></div><div class="modal"><div class="b"></div><div class="t"></div><div class="l"></div><div class="r"></div><div class="tl"></div><div class="tr"></div><div class="br"></div><div class="bl"></div><div class="modal_cont"><div class="modal_head"><h3>Title</h3><a href="#" class="modal_close" title="Close">Close</a></div><div class="modal_body"></div></div></div>');

    newModal.find(".modal_body").append($(">*", modalElement));
    $(modalElement).append(newModal);
    //$(document.body).prepend(modalElement);
    newModal = $(modalElement);
    newModal.hide();
    newModal.find(".tl").css({ width: dims.tl.w + "px", height: dims.tl.h + "px" });
    newModal.find(".tr").css({ width: dims.tr.w + "px", height: dims.tr.h + "px", marginLeft: (width - dims.tr.w) + "px" });
    newModal.find(".br").css({ width: dims.br.w + "px", height: dims.br.h + "px", marginLeft: (width - dims.tr.w) + "px", marginTop: (height - dims.br.h) + "px" });
    newModal.find(".bl").css({ width: dims.bl.w + "px", height: dims.bl.h + "px", marginTop: (height - dims.br.h) + "px" });
    newModal.find(".t").css({ marginLeft: (dims.tl.w) + "px", width: (width - dims.tl.w - dims.tr.w) + "px", height: dims.t.h + "px" });
    newModal.find(".b").css({ marginLeft: (dims.tl.w) + "px", width: (width - dims.tl.w - dims.tr.w) + "px", marginTop: (height - dims.b.h) + "px", height: dims.b.h + "px" });
    newModal.find(".l").css({ marginTop: (dims.tl.h) + "px", height: (height - dims.tl.h - dims.bl.h) + "px", width: dims.l.w + "px" });
    newModal.find(".r").css({ marginTop: (dims.tl.h) + "px", height: (height - dims.tl.h - dims.bl.h) + "px", marginLeft: (width - dims.r.w) + "px", width: dims.r.w + "px" });
    newModal.find(".modal_cont").css({
        marginLeft: dims.inPad.l + "px",
        marginTop: (dims.inPad.t) + "px",
        width: (width - dims.inPad.l - dims.inPad.r) + "px",
        height: (height - dims.inPad.t - dims.inPad.b) + "px",
        backgroundColor: "white",
        position: "absolute"
    });

    /* Buttons placing script */
    var modalButtons = newModal.find(".modal_buttons");
    newModal.find(".modal_head").before();
    var modalButtonsInner = $('<div class="inner1"><div class="inner2"></div></div>');
    modalButtonsInner.find(".inner2").append(modalButtons.find(">*"));
    modalButtons.append(modalButtonsInner);
    modalButtons.css({ height: "50px", position: "absolute", top: "0px", width: (width - dims.r.w - dims.l.w) + "px", marginTop: (height - dims.b.h - dims.t.h - 50) + "px" });
    modalButtons.find(".buttonEngraved:last").css({ marginRight: "0px" });

    newModal.find(".modal_greyOut").css({ position: "fixed", top: "0px", left: "0px", width: "100%", height: "100%", backgroundColor: "black", opacity: 0.5 });
    newModal.find(".modal_greyOut").click( function() { if (closeClickedCallback != null) closeClickedCallback();
        return false; } );
    //$(document.body).prepend(this.find(".modal_greyOut"));

    if (!browser.isIE6x)
        newModal.find(".modal").css({ width: width + "px", marginLeft: -(width / 2) + "px", marginTop: -(height / 2) + "px", position: "fixed" });
    else
        newModal.find(".modal").css({ width: width + "px", marginLeft: (width / 2) + "px", marginTop: (height / 2) + "px", position: "fixed" });
    newModal.find(".modal_head h3").text($(modalElement).attr("title"));
    if ($("dfn", modalElement).length > 0)
        newModal.find(".modal_head h3").html($("dfn", modalElement).html());
    $("dfn", modalElement).remove();
    newModal.find(".modal_close").click(function () {

        if (closeClickedCallback != null) closeClickedCallback();
        return false;
    });
    if (!showClose) $(modalElement).find(".modal_close").hide();

    //        this.sayHi = function () {
    //            alert("hi");
    //        };
    modalElement.modal = newModal;
    this.modalElement = modalElement;
    this.jqModalElement = $(modalElement);

};

$gluubF.modal.prototype = {
    open: function () {
        if (!$gluubF.modal.modalOpen) {
            $gluubF.modal.modalOpen = true;
            this.jqModalElement.show();
            //IE6 fix
            this.jqModalElement.find(".inner2").css({ width: this.jqModalElement.find(".inner1").outerWidth() + "px" });
        }
    },
    close: function () { this.jqModalElement.hide(); $gluubF.modal.modalOpen = false; },
    lock: function () { this.jqModalElement.find(".modal_body,modal_buttons").hide(); },
    unlock: function () { this.jqModalElement.find(".modal_body,modal_buttons").show(); },
    find: function (query) { return this.jqModalElement.find(query); }
};
$gluubF.modal.modalOpen = false;
$gluubF.modal.openModalName = "";
