﻿
/*
*= Budgivning
*/

var BidsHide = (function() {

	//cache elements
	this.elems = {
		container: '#divBudgivningContainer',
		bids_container: '#divBudgivningContainer ul',
		bids: '#divBudgivningContainer ul li'
	};
	
	//number of bids to view, starts with 0, i.e. 9 = 10
	this.max = 9;
	
	//cache this
	var self = this,
	
	//private timestamp-function
	_timestamp = function() {
		return new Date().getTime();
	},
	
	//private wait-function
	_wait = function(options) {
		options = $.extend({
			until: function() { return false; },
			success: function() { },
			error: function() { /* console.log('Error!') */ },
			timeout: 3000
		}, options);

		var start = _timestamp(),
				elapsed,
				now;

		window.setTimeout(function() {
			now = _timestamp();
			elapsed = now - start;
			if (options.until(elapsed)) {
				options.success();
				return false;
			}

			if (now >= start + options.timeout) {
				options.error();
				return false;
			}
			window.setTimeout(arguments.callee, 2);
		}, 2);

	},
	//private _init
	_init = function() {
		//cache number of bids
		self.elems.bids_len = $(self.elems.bids).length;
		if(self.elems.bids_len > 4) {
			//cache jQuery-elements and create new elements
			self.elems = {
				container : $(self.elems.container),
				bids_container : $(self.elems.bids_container),
				bids : $(self.elems.bids),
				bids_len: self.elems.bids_len,
				bids_hidden: $(self.elems.bids).filter(':gt(4)'),
				hidden_bids_container: $(document.createElement('ul')).attr('id', 'bidsHidden'),
				toggleBids: $(document.createElement('div')).attr('id', 'toggleBids').addClass('expand').html('<span>Visa alla '+ self.elems.bids_len +' bud</span>')
			}

			
			self.elems.bids_hidden
				.remove();
				
			self.elems.container

				.append(self.elems.hidden_bids_container);
				
			self.elems.container.parent()
				.after(self.elems.toggleBids)
							
			self.elems.hidden_bids_container
				.append(self.elems.bids_hidden);
				
			$('#toggleBids').bind('click', function(e) {
				$('#bidsHidden').slideToggle(250);
				if($(this).hasClass('expand')) {
					$(this).find('span').text('Visa färre bud');
					$(this).removeClass('expand');
				}
				else {
					$(this).find('span').text('Visa alla '+ self.elems.bids_len +' bud');
					$(this).addClass('expand');
				}
			});
		}
	};
	
	return {
		init: function() {
			_wait({
                until: function() {
                    return $(self.elems.bids).length > 0;
                },
                success: function() {
						_init();
                },
                timeout: 50000
            });

		}
	}
})();


/***												************************
****		PAGE LOAD						************************
****												************************/

$(document).ready(function () {

    /*** KONSTRUKTORER **/
    costrNojd();
    BidsHide.init();

});

/***												************************
****		NÖJD KAMPANJ				************************
****												************************/

var nojdBox;
var nojdExpanderBox;
var nojdBoxHeight;
var emergencyBrakeLink;
var nojdBoxTextArea;
var nojdBoxTextAreaDefText;
//var nojdWarantyPrintLink;
var abortCampain;

function costrNojd() {
	/*** ELEMENT VARIBALS ***/
	nojdBox = $("#nojdBox");
	nojdBoxTextArea = $("#nojdBox textarea");
	nojdBoxTextAreaDefText = nojdBoxTextArea.val();
	nojdExpanderBox = $("#nojdExpanderBox");
	nojdBoxHeight = nojdBox.height();
	emergencyBrakeLink = $("#emergencyBrakeLink");
	//nojdWarantyPrintLink = $("#nojdWarantyPrint");
	abortCampain = $("#nojdExpanderBox");

	/**** EVENT BINDERS ***/
	emergencyBrakeLink.bind("click", emergencyBrakeLinkClicked);
	nojdBoxTextArea.bind("focus", nojdTextAreaFocusAndBlur);
	nojdBoxTextArea.bind("blur", nojdTextAreaFocusAndBlur);
	nojdBoxTextArea.bind("blur", nojdTextAreaFocusAndBlur);
	//nojdWarantyPrintLink.bind("click", nojdWarantyPrintClicked);
	abortCampain.bind("click", abortCampainClicked);
}


function abortCampainClicked() {

	nojdBoxTextArea.unbind("focus");
	nojdBoxTextArea.unbind("blur");
	
	if (nojdBoxTextArea.html() == nojdBoxTextAreaDefText || nojdBoxTextArea.html() == "" )
	{
		nojdBoxTextArea.html("");
	}

	//alert( nojdBoxTextArea.html() );
	
}

/*function nojdWarantyPrintClicked() {
	window.print();
	return false;
}*/

function emergencyBrakeLinkClicked(e) {
	nojdExpanderBox.fadeIn();
}

function nojdTextAreaFocusAndBlur(e) {
	if (nojdBoxTextArea.val() == nojdBoxTextAreaDefText) {
		nojdBoxTextArea.val("");
	}
	else if (nojdBoxTextArea.val() == "") {
		nojdBoxTextArea.val(nojdBoxTextAreaDefText);
	}
}



//---- SHOW AND HIDE THE SAVED ITEMS MENU

//Define Timeout variable
var savedItemsTimeout;

$(document).ready(function () {

    //Is the user at "Mina sidor"?
    if (window.location.toString().toLowerCase().indexOf("/minsida/") > 0) {
        setTimeout(function () {
            showSavedItems(true);
        }, 10);
    }
    else {

        $("#savedItemsButton,#savedItemsMenu").hover(
        function () {
            showSavedItems();
        },
        function () {
            savedItemsTimeout = setTimeout(function () {
                hideSavedItems();
            }, 800);
        });

    }

});

function showSavedItems(noAnimation) {

    //Clear hide timeout
    clearTimeout(savedItemsTimeout);

    //Check so that menu isn't already displayed
    if ($("#savedItemsMenu").width() == 0) {

        //Set menu position
        var menuPosition = 900 - $("#savedItemsButton").position().left;
        $("#savedItemsMenu").css("right", menuPosition);

        //Calculate width

        //Reset all elements to be able to get correct content width
        $("#savedItemsMenu").css({
            "width": "auto",
            "visibility": "hidden"
        });
        $("#savedItemsMenu li").css("marginLeft", "0px");
        var menuWidth = $("#savedItemsMenu").width();
        
        //Calculate width with li margin accounted for
        $("#savedItemsMenu li").css("marginLeft", "");
        menuWidth = menuWidth + (parseInt($(".usercontrols li").css("margin-left")) * $("#savedItemsMenu li").length);
       
        //Reset CSS
        $("#savedItemsMenu").css({
            "width": "",
            "visibility": "visible"
        });

        //Animate or display
        if (noAnimation !== true) {
            $("#savedItemsMenu").animate({ width: menuWidth }, 300);
        }
        else {
            $("#savedItemsMenu").css("width",menuWidth);
        }

    }

}

function hideSavedItems() {

    $("#savedItemsMenu").animate({ width: "0px" }, 300);

}

//PAGE-SPECIFIC FUNCTIONS AND FIXES

$(document).ready(function () {

    //--- HIDE THE USER CONTROLS AND MAIN MENU IF THE USER COMES FROM DIALOG TO VIEW THE MAP
    
    var windowLocation = window.location.href,
        urlUserId = getUrlParameter("UserID"),
	    fromDialog = getUrlParameter("f");

    if (urlUserId != "" && fromDialog == "d") {
        $(".userloggedin").hide();
        $(".usercontrols ul li").hide();
        $("#mainContainer #topbar a").attr("href", "#");
        $(".navigation .nav1").hide();
        $(".navigation .nav2").hide();
        $(".navigation .nav3").hide();
        $(".navigation .nav4").hide();
        $("#footer").hide();
    }

    //--- HIDE IMAGES ON HUVUDKONTORET-PAGE IF NO IMAGE WAS FOUND
    if(windowLocation.toLowerCase().indexOf("huvudkontoret") >= 0){
    
        $(".businesscard img").error(function(){
            $(this).hide();
        });

    }

});




