var S = new function() {

	this.baseUrl = '/';
    this.isLoggedIn = false;
    this.userName = '';
    this.userId = 0;
    this.paramUserName = '';
    this.avatarUrl = '';
    this.backgroundImage = '';
    this.backgroundTile = false;
    this.bookmark = "";
    this.bookmarkurl = "";
    this.browser = "";
    this.thanksOwned = 0;
    this.currency = null;
    this.ip = null;

    // thumbtip info container
    this.thumbtip_data = {};

    this.callback = null;

    this.controllerNames = {'shopper': true, 'ajax': true, 'favicon': true, 'first': true, 'item': true,
                            'login': true, 'register': true, 'search': true, 'set': true, 'static': true, 'user': true};

    var self = this;

    this.setPageBackground = function()
    {
        document.body.style.cssText = 'background-image: url(' + this.backgroundImage + ')';
        if ( this.backgroundTile ) {
            if ( document.body.className.search('tile') < 0 ) {
                document.body.className += ' tile';
            }
        }
    };

    this.getAvatarHtml = function(size)
    {
        var html='<img width="' + size + '" src="' + self.avatarUrl + '" alt="Me" />';
        return html;
    };

    this.drawSmallAvatar = function()
    {
        var html = self.getAvatarHtml(25);
        document.write(html);
    };

    this.drawBigAvatar = function()
    {
        var html = self.getAvatarHtml(60);
        document.write(html);
    };

    this.drawAvatarWithSize = function(size)
    {
        var html = self.getAvatarHtml(size);
        document.write(html);
    };

    this.drawSignOut = function()
    {
        if ( self.isLoggedIn ) {
            var html = '<a href="' + self.baseUrl + 'logout/">Sign out</a>';
            document.write(html);
        }
    };

    this.drawTimeInfo = function(inputTimestamp)
    {
        document.write(self.getTimeInfo(inputTimestamp));
    };

    this.drawHeaderLinks = function()
    {
    	document.write(self.getHeaderHtml());
    };

    this.getHeaderHtml = function()
    {
        var action = self.getPageAction();

        var html = new Array();
        html.push( '<div class="menu"><ul>' );
        if ( self.isLoggedIn ) {
        	html.push( '<li' );
            if ( action == 'me' ) html.push( ' class="act"' );
            html.push( '><a href="/'+self.userName+'/me/" alt="Your profile" title="Your profile">Home</a></li>' );
        }
        else {
        	html.push( '<li' );
        	if ( typeof(action) == 'undefined' ) html.push( ' class="act"' );
        	html.push( '><a href="/">Home</a></li>' );
        }
        html.push( '<li' );
        if ( action == 'search' ) html.push( ' class="act"' );
        html.push( '><a href="/search/" alt="Discover new products" title="Discover new products">Explore</a></li>' );

        html.push( '<li class="no' );
        if ( action == 'styleboards' ) html.push( ' act' );
        html.push( '"><a href="/styleboards/" alt="Create new styleboard" title="Create new styleboard">Styleboards</a></li>' );
        html.push( '</ul></div>' );

        if ( self.isLoggedIn ) {
        	html.push( '<div class="login-link"><a href="/logout/">Log out</a></div>' );
        	html.push( '<div class="login-link"><a href="/'+self.userName+'/profile/">Settings</a></div>' );
        	html.push( '<div class="user-link"><a href="/'+self.userName+'/me/">Hi, '+self.userName+'</a></div>' );
        }
        else {
        	html.push( '<div class="join-link"><a href="#" onclick="S.callback=\'S.redirect(\\\'me\\\')\';S.showLogin();return false;">Join Now!</a></div>' );
        	html.push( '<div class="login-link"><a href="#" onclick="S.callback=\'S.redirect(\\\'me\\\')\';S.showLogin();return false;">Login</a></div>' );
        }

        return html.join('');
    };

    this.getPageAction = function()
    {
        var url = window.location.pathname;
        var pathParts = url.split("/");
        if ( pathParts[1] == 'register' || pathParts[1] == 'login' || pathParts[1] == 'explore' || pathParts[1] == 'search' || pathParts[1] == 'styleboards' )
            return pathParts[1];
        else
            return pathParts[2];
    };

    this.urlFor = function(params)
    {
        var url = self.baseUrl;

        if ( typeof(params) == 'object' ) {
            url += params.controller + '/';
            if ( params.action )
                url += params.action + '/';
            if ( params.id )
                url += params.id + '/';

            // todo ... we need custom parameter support here
        }

        if ( typeof(params) == 'string' ) {
            url += params;
        }

        return url;
    };

    this.getTimeInfo = function(inputTimestamp)
    {
        var dateObj = new Date();
        var timestamp = Math.round(dateObj.getTime()/1000) - parseInt(inputTimestamp, 10);

        if(timestamp <= (1*3600)) {
            return 'just now';
        }
        if(timestamp > (1*3600) && timestamp <= (8*3600)) {
        	return 'some hours ago';
        }
        if(timestamp > (8*3600) && timestamp <= (16*3600)) {
            return 'today';
        }
        if(timestamp > (16*3600) && timestamp <= (40*3600)) {
        	return 'yesterday';
        }
        if(timestamp > (40*3600) && timestamp <= (80*3600)) {
        	return 'some days ago';
        }
        if(timestamp > (80*3600) && timestamp <= (160*3600)) {
        	return 'this week';
        }
        if(timestamp > (160*3600) && timestamp <= (320*3600)) {
        	return 'last week';
        }
        if(timestamp > (320*3600) && timestamp <= (720*3600)) {
            return 'this month';
        }
        if(timestamp > (720*3600) && timestamp <= (1440*3600)) {
        	return 'last month';
        }
        if(timestamp > (1440*3600) && timestamp <= (2160*3600)) {
        	return 'two months ago';
        }
        if(timestamp > (2160*3600) && timestamp <= (2880*3600)) {
        	return 'three months ago';
        }
        if(timestamp > (2880*3600) && timestamp <= (3600*3600)) {
        	return 'four months ago';
        }
        if(timestamp > (3600*3600) && timestamp <= (4320*3600)) {
        	return 'five months ago';
        }
        if(timestamp > (4320*3600) && timestamp <= (5040*3600)) {
        	return 'six months ago';
        }
        if(timestamp > (5040*3600) && timestamp <= (5760*3600)) {
        	return 'seven months ago';
        }
        if(timestamp > (5760*3600) && timestamp <= (6480*3600)) {
        	return 'eight months ago';
        }
        if(timestamp > (6480*3600) && timestamp <= (7200*3600)) {
        	return 'nine months ago';
        }
        if(timestamp > (7200*3600) && timestamp <= (7920*3600)) {
        	return 'ten months ago';
        }
        if(timestamp > (7920*3600) && timestamp <= (8640*3600)) {
        	return 'eleven months ago';
        }
        if(timestamp > (8640*3600) && timestamp <= (17280*3600)) {
        	return 'over a year ago';
        }
        else {
            return 'a long time ago';
        }
    };

    this.ifMe = function(user, f)
    {
        if ( self.isLoggedIn && user == self.userName ) {
            if ( typeof(f) == 'function' ) f();
            var html = '<span>';
        } else {
            var html = '<span style="display:none">';
        }
        document.write(html);
    };

    this.ifNotMe = function(user, f)
    {
        if ( !self.isLoggedIn || user != self.userName ) {
            if ( typeof(f) == 'function' ) f();
            var html = '<span>';
        } else {
            var html = '<span style="display:none">';
        }
        document.write(html);
    };

    this.ifMeById = function(userId, f)
    {
        if ( self.isLoggedIn && userId == self.userId ) {
            if ( typeof(f) == 'function' ) f();
            var html = '<span>';
        } else {
            var html = '<span style="display:none">';
        }
        document.write(html);
    };
    
    this.ifNotMeById = function(userId, f)
    {
    	if ( !self.isLoggedIn || userId != self.userId ) {
    		if ( typeof(f) == 'function' ) f();
    		var html = '<span>';
    	} else {
    		var html = '<span style="display:none">';
    	}
    	document.write(html);
    };

    this.ifLoggedIn = function(f)
    {
        if ( self.isLoggedIn ) {
            if ( typeof(f) == 'function' ) f();
            var html = '<span>';
        } else {
            var html = '<span style="display:none">';
        }
        document.write(html);
    };

    this.ifNotLoggedIn = function(f)
    {
        if ( self.isLoggedIn ) {
            if ( typeof(f) == 'function' ) f();
            var html = '<span style="display:none">';
        } else {
            var html = '<span>';
        }
        document.write(html);
    };

    this.endif = function()
    {
        document.write('</span>');
    };

    this.showBusyCursor = function()
    {
        $(document.body).setStyle({cursor: 'progress'});
    };

    this.showNormalCursor = function()
    {
        $(document.body).setStyle({cursor: 'default'});
    };

    this.showGoogleReference = function()
    {
    	if ( document.referrer ) {
    		if ( document.referrer.indexOf(".google.") == -1 ) {
    			return;
    		}
    	}
    	else {
    		// no referer
    		return;
    	}

    	var decoded = decoreURI(document.referrer);
    	var matches = decoded.match("q=([^&]*)");
    	if ( matches && matches.length ) {
    	    // show the message
    	    var i, message = "", words = matches[1].replace(/\+/g, " ").split(" ");

    	    message = "Google said that you'r looking for ";
    	    for ( i = 0 ; i < words.length ; i++ ) {
    	    	message += '<a href="/search/?search=' + words[i] + '">' + words[i] + '</a> ';
    	    }
    	    message += ' ?';

    	    var node = document.getElementById('message');
    	    node.innerHTML = message;
    	    node.style.display = '';
    	}
    };

    this.showTwitterReference = function()
    {
    	if ( S.isLoggedIn == false && document.referrer.indexOf('twitter.com') > 0 ) {
    		var message = 'You can log into sfeed using your twitter account <a href="/login/twitter">right here</a>';

            var node = document.getElementById('message');
            if ( node ) {
	            node.innerHTML = message;
	            node.style.display = '';
            }
    	}
    };

    this.showThanksLeft = function()
    {
    	document.write("<strong id='thanks_left'>" + S.thanksOwned + "</strong>");
    };

    this.showThanksTable = function(thanksUserId, thanksAmount, type)
    {
    	var display, buttonCode, thanksIntroCode, divClass, btnClass;

    	if ( type == 'small' ) {
    		divClass = 'thanks-score-gray-small';
    		btnClass = 'btn-thanks-small';
    	}
    	else {
            divClass = 'thanks-score-gray';
            btnClass = 'btn-thanks';
    	}

    	if ( S.thanksOwned == 0 ) {
    	    display = '';
    	    buttonCode = '<div class="' + divClass + '">' + thanksAmount + '</div>';
    	    thanksIntroCode = '';
    	}
    	else {
    	    display = 'none';
    	    buttonCode = '<a id="user_thanks_received-' + thanksUserId + '" href="javascript:void(0);" onclick="S.giveThanksTo(this, ' + thanksUserId + ')" class="' + btnClass + '">' + thanksAmount + '</a>';
    	    thanksIntroCode = '<span id="thanks_intro">Click to give thanks,<br /></span>';
    	}

    	var msg = '';
    	if ( S.isLoggedIn ) {
    		msg =  'You have <strong id="user_thanks_owned-' + S.userId + '">' + S.thanksOwned + '</strong> left';
            msg += '<span id="more_thanks" style="display: ' + display + ';"><br /> <a href="#">Need more thanks?</a></span>';
    	}
    	else {
    		msg = '<a onclick="S.callback=\'window.location.reload()\';S.showLogin();return false;" href="#">Sign in</a> to give thanks';
    	}

        var html = '<table border="0" cellspacing="0" cellpadding="0">'+
            '<tr>'+
                '<td style="padding-right:10px">' +
                buttonCode +
                '</td>'+
                '<td class="f12">' +
                thanksIntroCode +
                msg +
                '</td></tr>'+
        '</table>';

        document.write(html);
    };

    this.giveThanksTo = function(element, userId)
    {
    	if ( S.isLoggedIn == false ) {
    		S.showLogin();
    		return;
    	}

    	if ( self.thanksOwned > 0 ) {
    		url = '/ajax/give_thanks';

    		p = new Object();
    		p.method = 'POST';
    		p.parameters = {to_user: userId};
    		p.onSuccess  = function(response) { self.giveThanksToCallback(response, element); };

    		new Ajax.Request(url, p);
    	}
    	else {
    		alert('You have no thanks to give out! You must earn thanks from others!');
    	}
    };

    this.giveThanksToCallback = function(response, element)
    {
    	var obj = response.responseText.evalJSON();

    	if ( obj.status ) {
    		S.thanksOwned--;

    		var elem;

    		elem = document.getElementById("user_thanks_owned-" + obj.from_user);
    		if ( elem )
    		    elem.innerHTML = S.thanksOwned;

    		elem = document.getElementById("user_thanks_received-" + obj.to_user);
    		if ( elem )
    		    elem.innerHTML = (parseInt(elem.innerHTML, 10) + 1);

    		if ( S.thanksOwned == 0 ) {
    			// disable the button when there are no more thanks
    			if ( elem )
    			    S.disableThanks(elem, obj.from_user);
    		}

    		if ( !parseInt(element.innerHTML, 10) ) {
    			element.innerHTML = 'Done';
    			element.onclick = '';
    		}
    	}
    	else {
    		alert(obj.error);
    	}
    };

    this.disableThanks = function(element, fromUserId)
    {
    	var thanksAmount = element.innerHTML;
    	if ( S.thanksOwned == 0 ) {
    		var elem = document.getElementById('user_thanks_owned-' + fromUserId);
    		elem.innerHTML = 'none';
    		elem.className = 'red';
    	}

    	if ( element.className.indexOf('-small') > 0 )
    	    element.parentNode.innerHTML = '<div class="thanks-score-gray-small">' + thanksAmount + '</div>';
    	else
    	    element.parentNode.innerHTML = '<div class="thanks-score-gray">' + thanksAmount + '</div>';

    	var elem = document.getElementById('more_thanks');
    	if ( elem )
    	   elem.style.display = '';

    	elem = document.getElementById('thanks_intro');
    	if ( elem )
    	   elem.style.display = 'none';
    };

    this._getThumbtipContainer = function()
    {
    	var divElem;

    	divElem = document.getElementById('thumbtip_container');
    	if ( divElem )
    	   return divElem;

    	divElem = document.createElement('DIV');
    	var imgElem = document.createElement('IMG');
    	imgElem.style.width = '100px';
    	imgElem.style.height = '100px';
    	Element.observe(imgElem, 'mousedown', function(event) { if (event.preventDefault){event.preventDefault(); }} );

    	divElem.setAttribute('id', 'thumbtip_container');
    	divElem.style.position = 'absolute';
    	divElem.style.display  = 'none';
    	divElem.style.zIndex   = 20000;
    	divElem.className = 'bigimage';

    	Element.observe(divElem, 'mouseout', self.hideThumbtip);
    	Element.observe(divElem, 'mousemove', SetEditor.moveDragDropSelector);
    	Element.observe(divElem, 'mouseup', SetEditor.unregisterDragOntoSet);
    	Element.observe(divElem, 'mousedown', self.onThumbtipClick);

    	divElem.appendChild(imgElem);

    	document.body.appendChild(divElem);

    	return divElem;
    };

    this.showThumbtip = function(event, url, itemId, itemPicture, itemTransPicture)
    {
    	if ( S.thumbtip_data["id"] ) {
    		clearTimeout(S.thumbtip_data["id"]);
    		S.hideThumbtip();
    	}

        var elem   = Event.element(event);
    	while ( elem.tagName != 'LI' ) {
    		elem = elem.parentNode;
    	}

        var offset = $(elem).cumulativeOffset();

        S.thumbtip_data["url"] = url;
        S.thumbtip_data["x"]   = offset.left - 30;
        S.thumbtip_data["y"]   = offset.top - 20;
    	S.thumbtip_data["id"] = setTimeout("S._showThumbtip()", 10);

    	S.thumbtip_data['item_id'] = itemId;
    	S.thumbtip_data['item_picture'] = itemPicture;
    	S.thumbtip_data['item_trans_picture'] = itemTransPicture;
    };

    this.onThumbtipClick = function(event)
    {
    	SetEditor.registerDragOntoSet(event, S.thumbtip_data['item_id'], S.thumbtip_data['item_picture'], S.thumbtip_data['item_trans_picture'], '');
    };

    this._showThumbtip = function()
    {
    	var tipContainer = S._getThumbtipContainer();

    	tipContainer.childNodes[0].src = S.thumbtip_data["url"];
    	tipContainer.childNodes[0].src = S.thumbtip_data["url"];
    	tipContainer.style.left = S.thumbtip_data["x"] + 'px';
    	tipContainer.style.top  = S.thumbtip_data["y"] + 'px';
    	tipContainer.style.display = '';
    };

    this.hideThumbtip = function()
    {
        if ( S.thumbtip_data["id"] ) {
            clearTimeout(S.thumbtip_data["id"]);
        }

    	var tipContainer = S._getThumbtipContainer();
    	tipContainer.style.display = 'none';
    	tipContainer.childNodes[0].src = '';
    };

    this.redirect = function(action)
    {
    	var href = '/'+S.userName+'/';
    	if ( action != null ) href += action + '/';
    	window.location.href = href;
    };

    
    /**
     * Login / Register popup
     */
    this.showLogin = function(backurl)
    {
    	url = "/login/popup_login/";
    	
        if ( backurl ) {
            url += "?backurl=" + backurl;
        }
        else {
        	var burl = window.location.pathname + window.location.search;
        	url += "?backurl=" + burl;
        }
        
    	self.showBusyCursor();
    	new Ajax.Request(url, {method: 'get', onSuccess: self.showLoginCallback});
    };

    this.showLoginCallback = function(response)
    {
    	Modalbox.show(response.responseText, {
    		title: 'Register / Sign in', 
    		overlayDuration: 0.1, 
    		slideDownDuration: 0.1, 
    		slideUpDuration: 0.1, 
    		resizeDuration: 0.1, 
    		width: 700, 
    		height:310});
    	self.showNormalCursor();
    };

    this._closeBox = function(event) {
    	Modalbox.hide();
    };

    this.closeBox = this._closeBox;

	// number formatting function
	// copyright Stephen Chapman 24th March 2006, 22nd August 2008
	// permission to use this function is granted provided
	// that this copyright notice is retained intact
	this.formatNumber = function(num,dec,thou,pnt,curr1,curr2,n1,n2) {var x = Math.round(num * Math.pow(10,dec));if (x >= 0) n1=n2='';var y = (''+Math.abs(x)).split('');var z = y.length - dec; if (z<0) z--; for(var i = z; i < 0; i++) y.unshift('0'); if (z<0) z = 1; y.splice(z, 0, pnt); if(y[0] == pnt) y.unshift('0'); while (z > 3) {z-=3; y.splice(z,0,thou);}var r = curr1+n1+y.join('')+n2+curr2;return r;}
	
	this.convertPrice = function(price,currency) {
		var price = parseFloat(price,10);
		if (price <= 0) return 0;
		//convert price
		if(currency != S.country_currency) {
			var itemCurrencyRate = parseFloat(eval('S.'+currency),10);
	        var userCurrencyRate = parseFloat(eval('S.'+S.country_currency),10);
	        price = ( price / itemCurrencyRate) * userCurrencyRate;
		}
		return price;
	};
	
	this.showPrice = function(price,currency) {
		var x = S.convertPrice(price, currency);
		if (x > 0) {
			x = S.formatPrice(x);
		} else x = '&nbsp;';
		return x;
	};
	this.formatPrice = function(price,currency) {
		price = parseFloat(price,10) / 100;
		if (price == 0) return '&nbsp;';
		if ( price < 1 ) price = 1;
		if (typeof(currency)=='undefined') currency = S.country_currency; 
		return S.formatNumber(price,0,' ','','',' '+currency,'-','');
	};
};
