  window.fbAsyncInit = function() {
    FB.init({
      appId  : '127804043919888',//fcd7224035453b05726163276018009b',
      oauth: true,
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
    FB.Event.subscribe('edge.create', function(href, widget) {
                //alert('You liked ' + href);

						var params = "u=" + escape(href);
					    url = "/fbuser/likelog";

					    new Ajax.Request(
					    url,{
					         method:'post',
					         postBody:params,
					         onSuccess: function(transport){
					             var json = eval('('+transport.responseText+')');
					             if(json.Result==0){
									//alert(json.message);
									//window.location.href = window.location.href;
					             }else{
									alert('Could not connect to facebook:' + json.message);
					             }
					         },
					         onFailure: function(transport) {
					             alert("Server connection failure");
					             return;
					         }
					    }
					    );
            });
	FB.Event.subscribe('auth.authResponseChange', function(response) {
		    if (response.authResponse) {
		    	// The user has logged in, and the cookie has been set

						var params = "";
					    url = "/fbuser/login";

					    new Ajax.Request(
					    url,{
					         method:'post',
					         postBody:params,
					         onSuccess: function(transport){
					             var json = eval('('+transport.responseText+')');
					             if(json.Result==0){
									//alert(json.message);
									window.location.href = window.location.href;
                                                                        //alert('Could not connect to facebook:' + json.message);
					             }else{
                                                                        window.location.href = window.location.href;
									//alert('Could not connect to facebook:' + json.message);
					             }
					         },
					         onFailure: function(transport) {
					             alert("Server connection failure");
					             return;
					         }
					    }
					    );



		    } else {
		      // The user has logged out, and the cookie has been cleared
		      facebook_callbacklogout();
		    }
		  });
  };

  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
  function facebook_logout()
  {
  		FB.logout(function(response) {
		  // user is now logged out
		  facebook_callbacklogout();
		});

  }
  function facebook_callbacklogout()
  {
      var params = "";
        url = "/fbuser/logout";

        new Ajax.Request(
        url,{
             method:'post',
             postBody:params,
             onSuccess: function(transport){
                 var json = eval('('+transport.responseText+')');
                 if(json.Result==0){
                                    window.location.href = window.location.href;
                 }else{
                                    //alert('Could not connect to facebook:' + json.message);
                 }
             },
             onFailure: function(transport) {
                 alert("Server connection failure");
                 return;
             }
        }
        );
  	//alert("is logged out");
  }
  function sg_nofollow(gotourl)
  {
          document.location.href = gotourl;
  }
function facebook_syncfriends()
{

		var params = "";
        url = "/fbuser/syncfriends";

        new Ajax.Request(
        url,{
             method:'post',
             postBody:params,
             onSuccess: function(transport){
             	var json = eval('('+transport.responseText+')');
                 if(json.result==0){
					//alert(json.message);
					//window.location=window.location;
                 }else{
					//alert(json.message);
                     //msgBox("Error "+json.result + ":" +json.message);
                 }
             },
             onFailure: function(transport) {
                 alert("Server connection failure");
                 return;
             }
        }
        );
}

//other scripts than facebook
function filtersite(site_id)
{
	if(site_id>0)
	{
		msgBoxBlueMini("Wait a few seconds. Saving your personal settings.", null);
		//if all is set
		var params = "site_id="+escape(site_id);
        url = "/nsearch/settingsremovesinglesite";

        new Ajax.Request(
        url,{
             method:'post',
             postBody:params,
             onSuccess: function(transport){
             	var json = eval('('+transport.responseText+')');
                 if(json.result==0){
					//alert(json.message);
					window.location=window.location;
                 }else{
					alert(json.message);
                     //msgBox("Error "+json.result + ":" +json.message);
                 }
             	window.location=window.location;
             },
             onFailure: function(transport) {
                 alert("Server connection failure");
                 return;
             }
        }
        );
     }else
     {
     	alert("Error filtering.");
     }
}
function togglesubmenu(submenudivid) {
	if ($(submenudivid).style.display != 'none') {
		new Effect.Fade(submenudivid, {duration: 0.5});
	} else {
		//clear all first
		$('submenuFriends').style.display = 'none';
		$('submenuShopping').style.display = 'none';

		new Effect.Appear(submenudivid, {duration: 0.3});
	}
}
function toggledivs(dividshow, dividhide) {
	$(dividhide).style.display = 'none';
	$(dividshow).style.display = 'block';
}
function hidealldivsstartingwith(divstart, from_id, to_id)
{
	//alert(to_id);
	to_id = Math.floor(to_id);
	//alert(to_id);

	for(var i=from_id; i < to_id; i++){
		$(divstart+i).style.display = 'none';
	}

}
function changeToPink(selItem)
{

	if(selItem == 'favorites')
	{
		if($('clubSavedMenuFavorites').hasClassName('clubSavedMenuGrey'))
			$('clubSavedMenuFavorites').removeClassName('clubSavedMenuGrey');
		if(!$('clubSavedMenuFavorites').hasClassName('clubSavedMenuPink'))
			$('clubSavedMenuFavorites').addClassName('clubSavedMenuPink');

		if($('clubSavedMenuFavoritesLink').hasClassName('csLeft'))
			$('clubSavedMenuFavoritesLink').removeClassName('csLeft');
		if(!$('clubSavedMenuFavoritesLink').hasClassName('csLeftPink'))
			$('clubSavedMenuFavoritesLink').addClassName('csLeftPink');

		if($('clubSavedMenuCollages').hasClassName('clubSavedMenuPink'))
			$('clubSavedMenuCollages').removeClassName('clubSavedMenuPink');
		if(!$('clubSavedMenuCollages').hasClassName('clubSavedMenuGrey'))
			$('clubSavedMenuCollages').addClassName('clubSavedMenuGrey');

		if($('clubSavedMenuCollagesLink').hasClassName('csRightPink'))
			$('clubSavedMenuCollagesLink').removeClassName('csRightPink');
		if(!$('clubSavedMenuCollagesLink').hasClassName('csRight'))
			$('clubSavedMenuCollagesLink').addClassName('csRight');
	}
	else if(selItem == 'collages')
	{

		if($('clubSavedMenuFavorites').hasClassName('clubSavedMenuPink'))
			$('clubSavedMenuFavorites').removeClassName('clubSavedMenuPink');
		if(!$('clubSavedMenuFavorites').hasClassName('clubSavedMenuGrey'))
			$('clubSavedMenuFavorites').addClassName('clubSavedMenuGrey');


		if($('clubSavedMenuFavoritesLink').hasClassName('csLeftPink'))
			$('clubSavedMenuFavoritesLink').removeClassName('csLeftPink');
		if(!$('clubSavedMenuFavoritesLink').hasClassName('csLeft'))
			$('clubSavedMenuFavoritesLink').addClassName('csLeft');

		if($('clubSavedMenuCollages').hasClassName('clubSavedMenuGrey'))
			$('clubSavedMenuCollages').removeClassName('clubSavedMenuGrey');
		if(!$('clubSavedMenuCollages').hasClassName('clubSavedMenuPink'))
			$('clubSavedMenuCollages').addClassName('clubSavedMenuPink');

		if($('clubSavedMenuCollagesLink').hasClassName('csRight'))
			$('clubSavedMenuCollagesLink').removeClassName('csRight');
		if(!$('clubSavedMenuCollagesLink').hasClassName('csRightPink'))
			$('clubSavedMenuCollagesLink').addClassName('csRightPink');

	}
}

function set_active_favorite_category(cat_id)
{
	var params = "cat_id="+escape(cat_id);
    url = "/nsearch/setactivefavoritecategory";

    new Ajax.Request(
    url,{
         method:'post',
         postBody:params,
         onSuccess: function(transport){
             var json = eval('('+transport.responseText+')');
             if(json.Result==0){
             	window.location = window.location;

				//alert(json.message);
             }else{
				alert(json.message);
                 //msgBox("Error "+json.Result + ":" +json.message);
             }
         },
         onFailure: function(transport) {
             alert("Server connection failure");
             return;
         }
    }
    );
}
function set_all_fb_likes()
{
    var likedivs = $$('div.fiFbLikeInner');
    var i=0;
    if(likedivs!=undefined)
    {
        for(i=0;i<likedivs.length;i++)
        {
            //alert($(likedivs[i].id+'_inner').innerHTML);
            var url = $(likedivs[i].id+'_inner').innerHTML;
            //alert(url);
            //likedivs[i].innerHTML = "<iframe src=\"http://www.facebook.com/plugins/like.php?href=" + escape(url) +"&amp;layout=button_count&amp;show_faces=false&amp;width=47&amp;action=like&amp;colorscheme=light&amp;height=20\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:47px; height:20px;\" allowTransparency=\"true\" >";
            likedivs[i].innerHTML = "<iframe src=\"/nsearchiframe/likebutton?href=" + escape(url) +"\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:47px; height:20px;\" allowTransparency=\"true\" >";
        }
    }

}
function load_ads_right()
{
    var adDiv = $('adUnderShoppingguide');
    if(adDiv!=undefined)
    {
        adDiv.innerHTML='<iframe src="/advertisingiframe/right" width="273px" height="1620px" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"/>';
    }else
    {
        adDiv = $('adUnder');
        if(adDiv!=undefined)
        {
            adDiv.innerHTML='<iframe src="/advertisingiframe/right" width="273px" height="1260px"  scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"/>';
        }
    }
}
function load_ads_top()
{
    return;
    var adDiv = $('adTopBanner');
    if(adDiv!=undefined)
    {
        adDiv.innerHTML='<iframe src="/advertisingiframe/top" width="996px" height="126px" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"/>';
    }
}


function DigeshopsMainController(){
    var arrControllers;
    this.arrControllers = 0;
    this.listeners = false;


    this.addDiv = function(targetDiv, className){
        var target;
        if(!(target = $(targetDiv))){
            target = document.createElement('div');
            target.id = targetDiv;
            target.className = className;
            document.body.appendChild(target);
        }
        return target;
    }
    this.addChildDiv = function(parentDiv, targetDiv, className){
        var target;
        if(!(target = $(targetDiv))){
            target = document.createElement('div');
            target.id = targetDiv;
            target.className = className;
            $(parentDiv).appendChild(target);
        }
        else
        {//check parent
        	var parents = $(targetDiv).ancestors();
	        var parent = parents[0];
	        if(parent.id != parentDiv)
	        {
	        	//alert(parent.id+'!='+parentDiv);
	        	parent.removeChild($(targetDiv));
	        	//and add on correct place
	        	target = document.createElement('div');
	            target.id = targetDiv;
	            target.className = className;
	            $(parentDiv).appendChild(target);
	        }
	  		//parent.removeChild($('clubRemoveDiv'));
        }
        return target;
    }
    this.getPos = function(id){
        var parents = $(id).ancestors();

        var parent = parents[0];
        var topparent = parents[parents.length-1];
        // posDiv is used to find the position of the element
        var posDiv = document.createElement('div');
        Element.addClassName(posDiv,'pos');
        Element.insert($(id), {before:posDiv});
        posDiv.absolutize(posDiv);
        var pos = Element.cumulativeOffset(posDiv);
        parent.removeChild(posDiv);
        delete posDiv;
        return pos;
    }


    this.innerRequest = function(args){
        var param = args[1];
        switch(param){

            case "test":

                break;

        }

    }
    this.getController = function(controllerName){
        switch(controllerName){
            case "Product":
                return(this.arrControllers[0]);
                break;
            case "User":
                return(this.arrControllers[1]);
                break;
            case "Main":
                return(main);
                break;
        }
    }
    this.request = function(args){
        //log(args[0] + ":" + args[1]);
        name = args[0];
        var controller;
        switch(name){
            case "Product":
                controller = this.arrControllers[0];
                break;
            case "User":
                controller = this.arrControllers[1];
                break;
            case "Main":
                this.innerRequest(args);
                return;
                break;
        }
        controller.request(args);
    }
    this.load = function(name){
        document.write('<script src="/public/scripts/controllers/Digeshops/'+name+'Controller.js" type="text/javascript"></script>');
    }
    this.addControllers = function()
	{
//		this.load('Product');
//		this.load('User');

		this.arrControllers = new Array(
	        new ProductController(),
	        new UserController()
	   	 );
	   	//this.addControllerTimer = setTimeout('main.addControllerTick()',100);
	}
	this.addControllerTick = function()
	{
		anyleft = false;
		if(this.arrControllers[0]==null)
		{
			if(ProductController != undefined)
			{
				this.arrControllers[0] = new ProductController();
			}else
				anyleft = true;
		}
		if(this.arrControllers[1]==null)
		{
			if(UserController != undefined)
			{
				this.arrControllers[1] = new UserController();
			}else
				anyleft = true;
		}
		if(anyleft == false)
       		clearTimeout(this.addControllerTimer);
       	else
       		this.addControllerTimer = setTimeout('main.addControllerTick()',100);
	}
	this.searchSearchMainMenu = function()
	{//search box, upper left. Get values from input_header
		this.request(new Array('Product','search', '/nsearch',$F('input_header')));
	}
	this.searchSearchBar1 = function()
	{//search box, upper left. Get values from input_pSearchbar1
		this.request(new Array('Product','search', $F('input_pSearchbar1_urlbase'),$F('input_pSearchbar1_s'),$F('input_pSearchbar1_np'), $F('input_pSearchbar1_sale') ));
	}
	this.searchSearchBar2 = function()
	{
		//refine price. Get values from input_pSearchbar2
		this.request(new Array('Product','search', $F('input_pSearchbar2_urlbase'),$F('input_pSearchbar2_s'),$F('input_pSearchbar2_np'), $F('input_pSearchbar2_sale'), $F('input_pSearchbar2_sc'), $F('input_pSearchbar2_fromprice'), $F('input_pSearchbar2_toprice')));
	}
	this.searchSearchBar3 = function()
	{
		//search by color
		this.request(new Array('Product','search', $F('input_pSearchbar3_urlbase'),$F('input_pSearchbar3_s'),$F('input_pSearchbar3_np'), $F('input_pSearchbar3_sale'), $F('input_pSearchbar3_sc')));
	}
}

    var main = new DigeshopsMainController();
    var ProductController;
    var UserController;
    var IsBodyLoaded = false;

    main.addControllers();

function afterLoad(){
	//Main search
    if($('input_header')!=undefined){
    Event.observe('input_header','keypress',function(event){
                   if(event.keyCode==Event.KEY_RETURN){
                   		//$('input_container').submit();
                   		main.searchSearchMainMenu();
                   }
                });
    }
    //Search bar, search
    if($('input_pSearchbar1_s')!=undefined){
    Event.observe('input_pSearchbar1_s','keypress',function(event){
                   if(event.keyCode==Event.KEY_RETURN){
                   		//$('input_container_pSearchbar1').submit();
                   		main.searchSearchBar1();
                   }
                });
    }

    //Search bar, refine by price, from price
    if($('input_pSearchbar2_fromprice')!=undefined){
    Event.observe('input_pSearchbar2_fromprice','keypress',function(event){
                   if(event.keyCode==Event.KEY_RETURN){
                   		//$('input_container_pSearchbar2').submit();
                   		main.searchSearchBar2();
                   }
                });
    }

    //Search bar, refine by price, to price
    if($('input_pSearchbar2_toprice')!=undefined){
    Event.observe('input_pSearchbar2_toprice','keypress',function(event){
                   if(event.keyCode==Event.KEY_RETURN){
                   		//$('input_container_pSearchbar2').submit();
                   		main.searchSearchBar2();
                   }
                });
    }
    
    IsBodyLoaded = true;
    setTimeout("load_ads_right()",50);
    setTimeout("load_ads_top()",150);
    
    //set_all_fb_likes();
}
function ProductController(){
	var curLang = 'en';
	this.gotoPage2 = function(page,pageBase){
		var params = pageBase + page;
		window.location.href = params;
	}

	// Funktioner f�r stora produktbilden i listningen: START
	this.hideLargeImage = function(){
        Event.stopObserving('largeImage','mouseover',this.bClearHideLargeImage);
        Event.stopObserving('largeImage','mouseout',this.bInitHideLargeImage);
		if(this.largeImageEvents != undefined){
			while(this.largeImageEvents.length>0){
				var id = this.largeImageEvents.pop();
		        Event.stopObserving(id,'mouseout',this.bInitHideLargeImage);
		        Event.stopObserving(id,'mouseover',this.bClearHideLargeImage);

			}
		}
		Element.hide('largeImage');
	}
	this.clearHideLargeImage = function(){
        if(this.largeImageTimer){
            clearTimeout(this.largeImageTimer);
            this.largeImageTimer = false;
        }
	}
	this.initHideLargeImage = function(){
		if(!this.largeImageTimer){
			this.largeImageTimer = setTimeout('main.request(new Array("Product","hideLargeImage"))',500);
		}else{
			clearTimeout(this.largeImageTimer);
		}
	}
	// Funktioner f�r stora produktbilden i listningen: SLUT

	// Funktioner f�r hover i klubben: START
	this.hideClubRemove = function(){
        Event.stopObserving('clubRemoveDiv','mouseover',this.bClearHideClubRemove);
        Event.stopObserving('clubRemoveDiv','mouseout',this.bInitHideClubRemove);
		if(this.clubRemoveEvents != undefined){
			while(this.clubRemoveEvents.length>0){
				var id = this.clubRemoveEvents.pop();
		        Event.stopObserving(id,'mouseout',this.bInitHideClubRemove);
		        Event.stopObserving(id,'mouseover',this.bClearHideClubRemove);

			}
		}
		Element.hide('clubRemoveDiv');

	}
	this.clearHideClubRemove = function(){
        if(this.clubRemoveTimer){
            clearTimeout(this.clubRemoveTimer);
            this.clubRemoveTimer = false;
        }
	}
	this.initHideClubRemove = function(){
		if(!this.clubRemoveTimer){
			this.clubRemoveTimer = setTimeout('main.request(new Array("Product","hideClubRemove"))',500);
		}else{
			clearTimeout(this.clubRemoveTimer);
		}
	}
	// Funktioner f�r hover i klubben: SLUT

    this.request = function(args){
        name = args[1];
        url = "/Product/";
        //log(name);
        switch(name){
            case "test":
                var target = 'product_info';
                $(target).innerHTML = '<center>Hej!</center>';
                centerAppear(target);
            break;
            case "showLargeImage":
            	this.clearHideLargeImage();
            	var product_id = args[3];
            	var w = args[4];
            	var h = args[5];
            	var div = main.addDiv('largeImage','largeImage');
				div.innerHTML = "<a href='/nsearch/singleproduct?pid="+product_id+"'><img src='"+args[2]+"' width='"+w+"' height='"+h+"px' border=0></a>";

 //            	div.innerHTML = "<img src='"+args[2]+"'>";
		    	div.style.position = 'absolute';
		    	div.style.zIndex = '15';
				var pos = main.getPos('thumb_'+product_id);

				var scroll = document.viewport.getScrollOffsets();
				var screenWidth = (window.innerWidth!=undefined?window.innerWidth:document.body.clientWidth);
				var screenHeight = (window.innerHeight!=undefined?window.innerHeight:document.body.clientHeight);
					//alert(screenWidth + ":" + screenHeight);return;
				if(screenWidth-pos.left-130+w>pos.left-w){
					div.style.left = (pos.left+180)+"px";
				}else{
					div.style.left = (pos.left-w-20)+"px";
				}

				if(pos.top-scroll.top+100 > screenHeight - (pos.top-scroll.top)){
					if(pos.top+100-h - scroll.top>0)
						div.style.top = (pos.top+100-h) + 'px';
					else
						div.style.top = scroll.top + "px";
				}else{
					div.style.top = pos.top + 'px';
				}
		    	//div.innerHTML = (pos.top + ":" + scroll.top +":" +screenHeight);
				div.style.display = 'block';


		        if(this.bInitHideLargeImage==undefined){
		            this.bInitHideLargeImage = this.initHideLargeImage.bindAsEventListener(this);
		            this.bClearHideLargeImage = this.clearHideLargeImage.bindAsEventListener(this);
		        }
		        Event.observe('largeImage','mouseout',this.bInitHideLargeImage);
		        Event.observe($('thumb_'+product_id),'mouseout',this.bInitHideLargeImage);
		        Event.observe('largeImage','mouseover',this.bClearHideLargeImage);
		        Event.observe($('thumb_'+product_id),'mouseover',this.bClearHideLargeImage);
		        if(this.largeImageEvents == undefined){
		        	this.largeImageEvents = new Array();
		        }
		        this.largeImageEvents.push('thumb_'+product_id);
            break;
            case "hideLargeImage":
            	this.hideLargeImage();
            break;
             case "hideClubRemove":
            	this.hideClubRemove();
            break;



            case "search":
                var params = '';
                if(args[3]!=null && args[3]!='')
                	params += 's='+escape(args[3])+'&';
                if(args[4]!=null && args[4]!='')
                	params += 'np='+escape(args[4])+'&';
                if(args[5]!=null && args[5]!='')
                	params += 'sale='+escape(args[5])+'&';
                if(args[6]!=null && args[6]!='')
                	params += 'sc='+escape(args[6])+'&';
                if(args[7]!=null && args[7]!='')
                	params += 'fromprice='+escape(args[7])+'&';
                if(args[8]!=null && args[8]!='')
                	params += 'toprice='+escape(args[8])+'&';
                var s_str = args[2]+'?'+params;
                //remove last &
                s_str = s_str.substring(0,s_str.length-1);


				//alert(s_str);return;
				window.location.href = s_str;
                return;
                if(curLang == 'sv')
                	msgBox('S&ouml;ker');
                else
                	msgBox('Searching');
                new Ajax.Request(
                    url,{
                         method:'post',
                         postBody:params,
                         onSuccess: function(transport){
                             var json = transport.responseText;
                             json = eval('('+json+')');
                             if(json.Result==0){
                                 hideBox();
                                $('mainContent').innerHTML = json.mainContent;

                                Event.observe('search_text','keydown',function(event){
								    if(event.keyCode==Event.KEY_RETURN){
								        main.request(new Array('Product','fullsearch'));
								 }
								 });
                             }else{
                             	 if(curLang == 'sv')
                                 	msgBox('Tyv&auml;rr uppstod ett fel. F&ouml;rs&ouml;k g&auml;rna igen.');
                                 else
                                 	msgBox('Sorry, there was an error. Please try again.');
                             }

                         },
                         onFailure: function(transport) {
                             if(curLang == 'sv')
                              	msgBox('Tyv&auml;rr uppstod ett fel. F&ouml;rs&ouml;k g&auml;rna igen.');
                             else
                              	msgBox('Sorry, there was an error. Please try again.');
                         }
                    }
                    );

            break;
            case "gotoPageDirect":
            	this.gotoPage2($F('gotopage')-1,args[2]);
            break;

            case "showHoverDiv":
            	//this.clearHideLargeImage();
            	var product_id = args[3];
            	var is_product = args[4];//product or collage
            	var name = args[5];
            	//var w = args[4];
            	//var h = args[5];
            	//var div = main.addChildDiv(args[2],'clubRemoveDiv', 'clubRemoveSmall');//parentDiv, targetDiv, className
            	var onclickCode='';
            	if(is_product==1)
            	{
            		onclickCode="main.request(new Array(\"User\",\"unfavorite\","+product_id+", \"club\"));";
            	}
            	var div = main.addChildDiv('fav_'+product_id,'clubRemoveDiv', 'clubRemoveSmall');//parentDiv, targetDiv, className
				div.innerHTML = "<div style='position:absolute;width:90px;height:30px;margin:1px;'>"
					+ "<div style='float:left;width:88px;height:14px;margin-left:4px;margin-top:3px;overflow:hidden;'>"+name+"</div>"
					+ "<div style='float:left;width:88px;height:13px;text-indent:50px;overflow:hidden;'>"
						+"<a style='color:#ee3377;' href='javascript:;' onclick='"+onclickCode+"'>Remove</a>"
					+"</div>"
					+ "</div>";

		    	div.style.position = 'relative';
		    	div.style.zIndex = '15';
				//var pos = main.getPos('fav_'+product_id);
				div.style.left = '10px';
				div.style.top = '40px';

				div.style.display = 'block';


		        if(this.bInitHideClubRemove==undefined){
		            this.bInitHideClubRemove = this.initHideClubRemove.bindAsEventListener(this);
		            this.bClearHideClubRemove = this.clearHideClubRemove.bindAsEventListener(this);
		        }
		        Event.observe('clubRemoveDiv','mouseout',this.bInitHideClubRemove);
		        Event.observe($('fav_'+product_id),'mouseout',this.bInitHideClubRemove);
		        Event.observe('clubRemoveDiv','mouseover',this.bClearHideClubRemove);
		        Event.observe($('fav_'+product_id),'mouseover',this.bClearHideClubRemove);
		        if(this.clubRemoveEvents == undefined){
		        	this.clubRemoveEvents = new Array();
		        }
		        this.clubRemoveEvents.push('fav_'+product_id);

            break;
        }

    }
}


function UserController(){
	var curLang = 'en';
    this.favorite = function(product_id, fromPage){
    	var url = "/fbuser/favorite";
    	var params = "pid="+product_id;
    	if(curLang == 'sv')
    		msgBoxBlueMini('Sparar som favorit...', null, 'Spara');
    	else
    		msgBoxBlueMini('Saving your favorite...', null, 'Save');
        new Ajax.Request(
            url,{
                 method:'post',
                 postBody:params,
                 onSuccess: function(transport){
                     var json = eval('('+transport.responseText+')');
                     if(json.Result==0){
                     	if(curLang == 'sv')
                         	msgBoxBlueMini("<br/>Produkten &auml;r sparad<br/>",2500, 'Spara');
                        else
                        	msgBoxBlueMini("<br/>The product was saved<br/>",2500, 'Save');
                         if(fromPage!=null && fromPage=='single')
                         {
	        				 var newStar = "<a href='javascript:;' onclick=\"main.request(new Array('User','unfavorite',"+product_id+",'single'));\">Favorite</a>";
	                         $('star_favorite_span_'+product_id).innerHTML = newStar;

	                         if($('star_favorite_span_'+product_id).hasClassName('productFav'))
								$('star_favorite_span_'+product_id).removeClassName('productFav');
							 if(!$('star_favorite_span_'+product_id).hasClassName('productFavIsFavorite'))
								$('star_favorite_span_'+product_id).addClassName('productFavIsFavorite');
                         }else
                         {
                         	 $('star_favorite_'+product_id).src='/public/Digeshops/images/finditem/favorite.png';
	                         var newStar = "<a class='fiFav' href='javascript:;' onclick=\"main.request(new Array('User','unfavorite',"+product_id+"));\" onmouseover=\"$('star_favorite_"+product_id+"').src='/public/Digeshops/images/finditem/favorite.png';\" onmouseout=\"$('star_favorite_"+product_id+"').src='/public/Digeshops/images/finditem/favorite.png';\"><img id='star_favorite_"+product_id+"' src='/public/Digeshops/images/finditem/favorite.png' width=\"49px\" height=\"44px\" align=\"bottom\" border=\"0\" class='transPng'></a>";
	                         $('star_favorite_span_'+product_id).innerHTML = newStar;
                         }
                     }else{
                     	if(curLang == 'sv')
                            msgBoxBlueSmall("Tyv&auml;rr kunde produkten inte sparas som favorit.<br/>F&ouml;rs&ouml;k igen senare!");
                      	else
                      		msgBoxBlueSmall("Sorry, the product could not be saved as a favorite.<br/>Try again later!");
                     }
                        //msgBox(str);
                 },
                 onFailure: function(transport) {
                     msgBoxBlueMini("<br/>Server connection failure");
                     return;
                 }
            }
            );
    }
    this.unfavorite = function(product_id, fromPage){
    	var url = "/fbuser/favorite";
    	var params = "pid="+product_id;
    	params += "&remove=1";
    	if(curLang == 'sv')
    		msgBoxBlueMini('<br/>Tar bort favorit...', null, 'Ta bort');
    	else
    		msgBoxBlueMini('<br/>Removing favorite...', null, 'Remove');
        new Ajax.Request(
            url,{
                 method:'post',
                 postBody:params,
                 onSuccess: function(transport){
                     var json = eval('('+transport.responseText+')');
                     if(json.Result==0){
                     	 if(curLang == 'sv')
                         	msgBoxBlueMini("Produkten borttagen fr&aring;n dina favoriter!",1000, 'Ta bort');
                         else
                         	msgBoxBlueMini("Your favorite was successfully removed!",1000, 'Remove');

                     	 if(fromPage!=null && fromPage=='club')
                         {
	        				//just remove 'fav_'+product_id
	        				Element.hide('fav_'+product_id);
	        				//alert('hide' + 'fav_'+product_id);
	        				return;
                         }else if(fromPage!=null && fromPage=='single')
                         {
	        				var newStar = "<div id='singlestardiv'><a href='javascript:;' onclick=\"main.request(new Array('User','favorite',"+product_id+",'single'));\">Favorite</a></div>";
	                        $('star_favorite_span_'+product_id).innerHTML = newStar;
	                       	if($('star_favorite_span_'+product_id).hasClassName('productFavIsFavorite'))
								$('star_favorite_span_'+product_id).removeClassName('productFavIsFavorite');
							if(!$('star_favorite_span_'+product_id).hasClassName('productFav'))
								$('star_favorite_span_'+product_id).addClassName('productFav');

                         }else
                         {
	                         var newStar = "<a class='fiFav' href='javascript:;' onclick=\"main.request(new Array('User','favorite',"+product_id+"));\" onmouseover=\"$('star_favorite_"+product_id+"').src='/public/Digeshops/images/finditem/favorite.png';\" onmouseout=\"$('star_favorite_"+product_id+"').src='/public/Digeshops/images/finditem/favorite_bw.png';\"><img id='star_favorite_"+product_id+"' src='/public/Digeshops/images/finditem/favorite_bw.png' width=\"49px\" height=\"44px\" align=\"bottom\" border=\"0\" class='transPng'></a>";
	                         $('star_favorite_span_'+product_id).innerHTML = newStar;
                         }
                     }else{
                     	 if(curLang == 'sv')
                       	 	msgBoxBlueSmall("Tyv&auml;rr kunde ta bort produkten fr&aring;n dina favoriter<br/>F&ouml;rs&ouml;k igen senare!");
                       	 else
                       	 	msgBoxBlueSmall("Sorry, your favorite could not be removed.<br/>Try again later!");
                     }
                        //msgBox(str);
                        return;
                 },
                 onFailure: function(transport) {
                     msgBoxBlueMini("<br/>Server connection failure");
                     return;
                 }
            }
            );
        return;
    }
    this.addtofavorites = function()//adds product using parsing of the url
	{
		url = "/fbuser/addfavoritebyurl";
		var params = "url="+escape(window.location.href);

        new Ajax.Request(
        	url,{
             method:'post',
             postBody:params,
             onSuccess: function(transport){
                 var json = eval('('+transport.responseText+')');
                 if(json.Result==0){
                 	if(curLang == 'sv')
                 		msgBoxBlueMini("<br/>Produkten &auml;r sparad<br/>",2500);
                 	else
                 		msgBoxBlueMini("<br/>The product is saved.<br/>",2500);
                 	product_id = json.product_id;
                 	var newStar = "<a href='javascript:;' onclick=\"main.request(new Array('User','unfavorite',"+product_id+"));\" onmouseover=\"$('star_favorite_"+product_id+"').src='/public/Digeshops/images/finditem/favorite_bw.png';\" onmouseout=\"$('star_favorite_"+product_id+"').src='/public/Digeshops/images/finditem/favorite.png';\"><img id='star_favorite_"+product_id+"' src='/public/Digeshops/images/finditem/favorite.png' width=\"49px\" height=\"44px\" align=\"bottom\" border=\"0\" class='transPng'></a>";
                         $('star_favorite_span_'+product_id).innerHTML = newStar;
                 }else{

                 }
             },
             onFailure: function(transport) {
                 msgBoxBlueMini("<br/>Server connection failure");
                 return;
             }
        	}
        );
	}
	this.removecollage = function(collage_id, fromPage){
    	var url = "/fbuser/removecollage";
    	var params = "cid="+collage_id;
    	params += "&remove=1";
    	if(curLang == 'sv')
    		msgBoxBlueMini('<br/>Tar bort collage...', null, 'Ta bort');
    	else
    		msgBoxBlueMini('<br/>Removing styleboard...', null, 'Remove');
        new Ajax.Request(
            url,{
                 method:'post',
                 postBody:params,
                 onSuccess: function(transport){
                     var json = eval('('+transport.responseText+')');
                     if(json.Result==0){
                     	 if(curLang == 'sv')
                         	msgBoxBlueMini("<br/>Collaget &auml;r borttaget",1000, 'Ta bort');
                         else
                         	msgBoxBlueMini("<br/>The styleboard is removed",1000, 'Remove');

                     	 if(fromPage!=null && fromPage=='club')
                         {
	        				Element.hide('collage_'+collage_id);
	        				return;
                         }
                     }else{
                     	 if(curLang == 'sv')
                         	msgBoxBlueSmall("Tyv&auml;rr kunde inte collaget tas bort.<br/>F&ouml;rs&ouml;k igen senare!");
                         else
                         	msgBoxBlueSmall("Sorry, your styleboard could not be removed.<br/>Try again later!");
                     }
                        //msgBox(str);
                        return;
                 },
                 onFailure: function(transport) {
                     msgBoxBlueMini("<br/>Server connection failure");
                     return;
                 }
            }
            );
        return;
    }

    this.request = function(args){
        name = args[1];
        url = "/User/";
        switch(name){
        	case "favorite":
        		//alert(args.length);
        		this.favorite(args[2], args[3]);
        		break;
        	case "unfavorite":
        		this.unfavorite(args[2], args[3]);
        		break;
        	case "addtofavorites":
        		this.addtofavorites();
        	break;
        	case "removecollage":
        		this.removecollage(args[2], args[3]);
        		break;
        }

    }
}
var getScrollY = function() {
  return window.pageYOffset ||
         (document.documentElement && document.documentElement.scrollTop) ||
         (document.body && document.body.scrollTop);
}
function createBlueBox(titleStr, innerStr){
    var div = document.createElement('div');
    Element.addClassName(div, 'bigBlueBox');
    document.body.appendChild(div);
    var titleDiv = document.createElement('div');
    Element.addClassName(titleDiv, 'bigBlueBoxTitle');
    titleDiv.innerHTML = titleStr;
    div.appendChild(titleDiv);
    var bodyDiv = document.createElement('div');
    Element.addClassName(bodyDiv, 'bigBlueBoxInner');

    if(typeof(innerStr)=="object"){
        bodyDiv.appendChild(innerStr);
    }else{
        bodyDiv.innerHTML = innerStr;
    }

    div.appendChild(bodyDiv);
    var closeDiv = document.createElement('div');
    Element.addClassName(closeDiv, 'bigBlueBoxClose');
    closeDiv.innerHTML = 'Close';
    div.appendChild(closeDiv);
    closeDiv.observe('click', function(e){e.currentTarget.parentNode.hide();});
    centerAppear(div);

}

function centerAppear(divId){
    ns4 = (document.layers)? true:false
    ie4 = (document.all)? true:false
    winW = (ns4)? window.innerWidth-16 : document.body.offsetWidth-20;
    Element.makePositioned(divId);
    d = $(divId).getDimensions();
    left = Math.round((winW-d.width)/2);
    $(divId).style.left = left + "px";

//  var x = 200;
  var y = 100;

  deltaY = getScrollY();
  y += deltaY;
  //Element.setStyle(divId,{top:y});
  $(divId).style.top = y + "px";

  Effect.Appear(divId,{'duration':0.9});
}
function msgBox(message, timer)
 {


  var msgbox = $('infoDiv');
  message = message + "<br>&nbsp;<br><center><a href='javascript:;' onclick='hideBox();'>Close</a></center>";
  msgbox.innerHTML = message;
    ns4 = (document.layers)? true:false
    ie4 = (document.all)? true:false
    winW = (ns4)? window.innerWidth-16 : document.body.offsetWidth-20;
    d = $('infoDiv').getDimensions();
    left = Math.round((winW-d.width)/2);
    var img = new Image();
    img.src= "/public/images/loader_ongrey.gif";
    $('infoDiv').style.left = left + "px";

//  var x = 200;
  var y = 200;
  deltaY = getScrollY();
  //alert(getScrollY());
  y += deltaY;
//  Element.setStyle('infoDiv',{left:x});
  //Element.setStyle('infoDiv',{top:y});
  $('infoDiv').style.top = y + "px";
  Effect.Appear('infoDiv',{'duration':0.2});
  if(timer){
      setTimeout("hideBox()",timer);
  }
 }
 function hideBox(message)
 {
  var msgbox = $('infoDiv');
  Element.hide('infoDiv');
 }
 function centerDiv(divId){
    ns4 = (document.layers)? true:false
    ie4 = (document.all)? true:false
    winW = (ns4)? window.innerWidth-16 : document.body.offsetWidth-20;
    d = $(divId).getDimensions();
    left = Math.round((winW-d.width)/2);

    $(divId).style.left = left + "px";

    var y = 200;
    deltaY = getScrollY();
    y += deltaY;

    $(divId).style.top = y + "px";
 }
  function msgBoxBlueLarge(message, timer)
 {
 	hideBoxBlueAll();
	  var msgbox = $('msgbox_l_div');
	  var msgspan = $('msgbox_l_span');
	  //message = message + "<br>&nbsp;<br><center><a href='javascript:;' onclick='hideBoxLarge();'>Close</a></center>";
	  msgspan.innerHTML = message;
	    ns4 = (document.layers)? true:false
	    ie4 = (document.all)? true:false
	    winW = (ns4)? window.innerWidth-16 : document.body.offsetWidth-20;
	    d = $('msgbox_l_div').getDimensions();
	    left = Math.round((winW-d.width)/2);

	    $('msgbox_l_div').style.left = left + "px";

	//  var x = 200;
	  var y = 200;
	  deltaY = getScrollY();
	  //alert(getScrollY());
	  y += deltaY;

	  $('msgbox_l_div').style.top = y + "px";
	  Effect.Appear('msgbox_l_div',{'duration':0.2});
	  if(timer){
	      setTimeout("hideBoxBlueLarge()",timer);
	  }
 }
 function msgBoxBeauty(message, title){
     hideBoxBlueAll();
     $('bBoxTop').innerHTML = "<p>" + title + "</p>";
     $('bBoxBody').innerHTML = message;
     Element.observe("bBox","click", function(){$('bBox').hide();});
     centerDiv("bBox");
     Element.setStyle('bBox',{display:'block'});
 }
 function helpFBConnect(){
     msgBoxBeauty("<p>Loading...</p>", "Loading...");
     new Ajax.Request("/feedsview/fbconnecthelpajax",{
                         method:'post',
                         onSuccess: function(transport){
                             var json = transport.responseText;
                             json = eval('('+json+')');
                             if(json.Result==0){
                                msgBoxBeauty(json.message, json.title);
                             }
                         }
     });
 }
 function hideBoxBlueLarge()
 {
	  var msgbox = $('msgbox_l_div');
	  Element.hide('msgbox_l_div');
 }
 function msgBoxBlueSmall(message, timer)
 {
 	hideBoxBlueAll();
	  var msgbox = $('msgbox_s_div');
	  var msgspan = $('msgbox_s_span');
	  //message = message + "<br>&nbsp;<br><center><a href='javascript:;' onclick='hideBoxSmall();'>Close</a></center>";
	  msgspan.innerHTML = message;
	    ns4 = (document.layers)? true:false
	    ie4 = (document.all)? true:false
	    winW = (ns4)? window.innerWidth-16 : document.body.offsetWidth-20;
	    d = $('msgbox_s_div').getDimensions();
	    left = Math.round((winW-d.width)/2);

	    $('msgbox_s_div').style.left = left + "px";

	//  var x = 200;
	  var y = 200;
	  deltaY = getScrollY();
	  //alert(getScrollY());
	  y += deltaY;

	  $('msgbox_s_div').style.top = y + "px";
	  Effect.Appear('msgbox_s_div',{'duration':0.2});
	  if(timer){
	      setTimeout("hideBoxBlueSmall()",timer);
	  }
 }
 function hideBoxBlueSmall()
 {
	  var msgbox = $('msgbox_s_div');
	  Element.hide('msgbox_s_div');
 }
 function msgBoxBlueMini(message, timer)
 {
     msgBoxBlueMini(message, timer, '');
 }
 function msgBoxBlueMini(message, timer, header)
 {
 	hideBoxBlueSmall();
 	hideBoxBlueLarge();
	  var msgbox = $('msgbox_mini_div');
	  var msgspan = $('msgbox_mini_span');
	  //message = message + "<br>&nbsp;<br><center><a href='javascript:;' onclick='hideBoxSmall();'>Close</a></center>";
	  msgspan.innerHTML = message;
          if(header)
          {
              var headerspan = $('msgbox_mini_span_header');
              headerspan.innerHTML = header;
          }


	    ns4 = (document.layers)? true:false
	    ie4 = (document.all)? true:false
	    winW = (ns4)? window.innerWidth-16 : document.body.offsetWidth-20;
	    d = $('msgbox_mini_div').getDimensions();
	    left = Math.round((winW-d.width)/2);

	    $('msgbox_mini_div').style.left = left + "px";

	//  var x = 200;
	  var y = 200;
	  deltaY = getScrollY();
	  //alert(getScrollY());
	  y += deltaY;

	  $('msgbox_mini_div').style.top = y + "px";
	  Effect.Appear('msgbox_mini_div',{'duration':0.2});
	  if(timer){
	      setTimeout("hideBoxBlueMini()",timer);
	  }
 }
 function hideBoxBlueMini()
 {
	  var msgbox = $('msgbox_mini_div');
	  Element.hide('msgbox_mini_div');
 }
 function hideBoxBlueAll()
 {
 	hideBoxBlueMini();
 	hideBoxBlueSmall();
 	hideBoxBlueLarge();
 }
function toggleshow(span_id){
	var div1 = document.getElementById(span_id)
	if (div1.style.display == 'none') {
		div1.style.display = 'block'
	} else {
		div1.style.display = 'none'
	}
}

function submitForm(formName){
    ns4 = (document.layers)? true:false
    ie4 = (document.all)? true:false
    if(ie4){
        $(formName).submit();
    }

}
function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");

    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

function isIE7Min(){
	return (getIEVersionNumber() >= 7);
}


CFnlHelper = Class.create({
initialize:function(){
this.texts = new Hash();
this.timers = new Hash();
this.curOver = [];
},
createAndShowHelperDiv:function(varId){
        var newId = varId+ '_FnlHelper';

        if($(newId)==undefined){
                var d = document.createElement('div');
                d.id = varId + '_FnlHelper';
                var pos = main.getPos(varId);
                var w = Element.getStyle(varId,'width').split('px')[0];
                var h = Element.getStyle(varId,'height').split('px')[0];
                var x = parseInt(pos[0]) + parseInt(w) - 70;
                var y = Math.round(parseInt(pos[1]) + h*0.90);
                Element.setStyle(d,{position:'absolute',top:y+'px',left:x+'px', display:'none'});
                Element.addClassName(d,'fnlHelperBubble');

                d.innerHTML = this.texts.get(varId);
                document.body.appendChild(d);
                Effect.Appear(newId,{duration:0.2});
                Event.observe(newId, 'mouseover', this.mouseOver.bind(this));
                Event.observe(newId, 'mouseout', this.mouseOut.bind(this));
        }
},
add:function(varId, str){
this.texts.set(varId,str);

var target = $(varId);
Event.observe(varId, 'mouseover', this.mouseOver.bind(this));
Event.observe(varId, 'mouseout', this.mouseOut.bind(this));
},
mouseOver:function(e){
        var id = Event.element(e).identify();
        if(id.indexOf('nonymo')>0)//try with current target if we cannot find div
        {
        	id = e.currentTarget.identify();
		}
        if(id.indexOf('_')>0){
                id = id.split('_')[0];
        }
        var t = this.timers.get(id+'_hide');
        if(t != undefined){
                clearTimeout(t);
                this.timers.unset(id+'_hide');
        }
        if(this.curOver.indexOf(id)<0){
                this.curOver.push(id);
                t = this.timers.get(id+'_show');
                if(t==undefined){
                        t = setTimeout("fnlHelper.showHelper('"+id+"');",1000);
                        this.timers.set(id + '_show', t);
                }
        }
},
showHelper:function(id){
        if(this.curOver.indexOf(id)>=0){
                this.createAndShowHelperDiv(id);
        }
},
hideHelper:function(id){
        if($(id+'_FnlHelper')!=undefined){
                Effect.Fade(id+'_FnlHelper',{duration:0.2,afterFinish:function(e){
                        Element.remove(e.element);
                }});
        }
        t = this.timers.get(id+'_hide');
        if(t!=undefined){
                this.timers.unset(id+'_hide');
        }
},
mouseOut:function(e){
        var id = Event.element(e).identify();
        if(id.indexOf('_')>0){
                id = id.split('_')[0];
        }

        if(this.curOver.indexOf(id)>=0){
                var i = this.curOver.indexOf(id);
                this.curOver.splice(i,1);
                var t = this.timers.get(id+'_show');
                if(t!=undefined){
                        clearTimeout(t);
                        this.timers.unset(id+'_show');
                }
                t = this.timers.get(id+'_hide');
                if(t==undefined){
                        t = setTimeout("fnlHelper.hideHelper('"+id+"');",1000);
                        this.timers.set(id + '_hide', t);
                }
        }
}
});

