$(function() {

	// get root
	var root  = $("base").attr("href");
	
	var loadingAnimation = '<div style="padding-top:10px;margin:0 auto;text-align:center;"><img src="/images/icons/loadingAnimation.gif" /></div>';

	//get user screen height
	var screen_height = screen.height;
	
	var height = screen_height - 120;
	
	//set max height
	if(height > 960)
		height = 880;
    
	$( ".datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
	
	//if(jQuery.boxy) {
		$(".modal").boxy({fixed:true, hideShrink:false, modal:true});
	//}
    
	
	/*****************************
	*
	* Generic common functions
	* 
	*****************************/
    
    // Radio buttons select for opening hours, dim target
    $(".radio_button").click(function(){
    
    	// get this input element
        var input = $(this).find("input[name='offer_opening_hours_override']");
		var all = $("input[name='offer_opening_hours_override']");
        
        if(input.length == 0) {
        	alert("erro");
            return false;
        }
        var value = input.val();
        
        // remove selected from all
    	$(".radio_button").removeClass("radio_selected");
        
        // add to this 
        $(this).addClass("radio_selected");
        
        // remove checking from both
        all.attr("checked", false);
        
        // add checked for this
		input.attr("checked", true);
        
        if(value == 1) {
        	
        	$(".dim_target").css("opacity", "0.2");
        }
        else {

        	$(".dim_target").css("opacity", "1");
        }
    });

	// Button as anchor
	$(".button_link").click(function(){
		var href = $(this).attr("href");
		
		window.location = href;
	});
	
	// Disable anchor or somthing else
	$(".disabled").click(function() {
		return false;
	});
	
	// Empty field on focus 
	$(".on_focus_empty").click(function(){
		var alt = $(this).attr("alt");
		if($(this).val() == alt) 
			$(this).val('');
		
	});
	
	// Set focus to field
	$(".set_focus").click(function(){
		var alt = $(this).attr("alt");
		$("input[name='" + alt + "']").addClass("red_border");
		$("input[name='" + alt + "']").focus();
		
		return false;
	});
	
	// Switch between tabs 
	$(".tab_switcher").click(function(){
		var href = $(this).attr("href");
		var parts = href.split("#");
		var target = parts[1];

		var target_element = $("#" + target);
		var hide_elements_class = $(this).attr("alt");

		//remove current
		$(".tab_switcher").removeClass("tab_switcher_current");
		
		//add class for just this
		$(this).addClass("tab_switcher_current");
		
		// show and hide
		$("." + hide_elements_class).hide();
		target_element.show();

		return false;
	});
	
	// Switch between divs
	$(".checkout_div_switcher").click(function(){
		var href = $(this).attr("href");
		var parts = href.split("#");
		var target = parts[1];
		
		var target_element = $("#" + target);
		var hide_elements_class = $(this).attr("alt");
				
		// show and hide
		$("." + hide_elements_class).hide();
		target_element.show();
		$(".checkout_tabs a").removeClass("current"); 
		$("#" + target + "_tab").addClass("current");
		$("#" + target + "_tab").removeClass("disabled");

		
		return false;
	});
	
	// Toggle an elements visibility
	$(".toggle_element").click(function(){

		$("#" + $(this).attr("alt")).toggle('fast');
		
		return false;
										
	});
	
	// Hide this
	$(".hide_this").click(function(){
		$(this).hide();
	});
	
	// Show popup confirm box
	$(".confirm_box, .confirm").click(function(){
		var string = $(this).attr("title");
		
		if( ! string)
			string = "Är du säker?";
			
		if(confirm(string))
			return true;
		return false;
	 });
	
	// Show confirm box with URL as destination
	$(".confirm_goto_url").click(function(){
		var string = $(this).attr("title");

		if( ! string)
			string = "Är du säker?";
			
		if(confirm(string))
			window.location = $(this).attr("href");
			
		return false;
	 });
	 
	 // Enable an element
	 $(".enable_element").click(function(){
	 	var alt = $(this).attr("alt");

		$("#" + alt).attr("disabled", false);
	 });
	 
	 // show hide more (with changed text values on link)
	 $(".show_more_text").click(function(){
		var target = $("#"+$(this).attr("data-target"));
		var link_text_before = $(this).attr("data-text");
		var link_text_after = $(this).attr("data-alttext");
		if($(this).hasClass("expanded")) {
			target.slideUp('fast');	 
			$(this).removeClass("expanded");
			$(this).text(link_text_before);
		}
		else {
			target.slideDown('fast');
			$(this).addClass("expanded");
			$(this).text(link_text_after);
		}

		return false;
	 });
	 
	 // Shows or hides a div
	 $(".show_hide_div").click(function(){
	 	var alt = $(this).attr("alt");
		var href = $(this).attr("href");
		var parts = href.split("#");
		var target = parts[1];
		var target_div = $("#" + target);
		
		if(alt == 'show' && target_div.hasClass("hidden")) {
			target_div.removeClass("hidden");
		}
		else if(alt == 'hide') {
			if( ! target_div.hasClass("hidden")) {
				target_div.addClass("hidden");
			}
		}
		
	 });
	
	
	// Set a text value 
	$(".set_input_value").click(function(){
		var id = $(this).attr("id");
		var alt = $(this).attr("alt");

		$("input[name='" + id + "']").val(alt);
	});
	
    
    
    // Date input checker for value not bigger/smaller than other
    
    /* usage:
     *
     * add an alt tag with name of the input to compare with
     * add a class "date_start" to the input which is the start date
     * add a class "date_end" to the input which is the end date
     *
     */
    $(".date_checker").change(function(){
    
    	var alt = $(this).attr("alt");
        var value = $(this).val();
        
        //alert("Alt:" + alt + ", val: " + value);
        
        if(alt) {
        	
            if($("input[name='" + alt + "']").length == 1)
	            var other = $("input[name='" + alt + "']").val();
            else
            	var other = $("select[name='" + alt + "']").val();
                       
            if($(this).hasClass("date_start")) {
            	if(value > other && other != '' && other != 0) {
                	alert("Too late!");
                    $(this).val(other);
                }
            
            }
            else if($(this).hasClass("date_end")) {
            	if(value < other && other != '' && other != 0) {
                	alert("Too soon!");
                    $(this).val(other);
                }
            }
        
        
        }
    
    });
	
	


	// TEST API JSON DEMO FUNCTIONS
    $("#load_api_data").click(function(){
		
        var input = new Array();
        
        input["device_id"] = "213123nnnnnb123";
        input["data"]["spot_latitude"] = 50.2323;
  
		//do the AJAX call via post
		$.post("http://rabble.se/admin/api/get_coupons/197285d1fd18ad428ee60d76b25b9fd2", { input: input },
			function(){
					$("#data").html(json);
		}, "json");

/*

        $.getJSON("http://rabble.se/admin/api/get_coupons/197285d1fd18ad428ee60d76b25b9fd2", { input: input }, function(json){
        	$("#data").html(json);
        });

		
		//do the AJAX call via post (json)
		$.post("/api/get_coupons", function(data){

		}, "json");
        
        
        $.getJSON('ajax/test.json', function(data) {
  		$('.result').html('<p>' + data.foo + '</p>'
    + '<p>' + data.baz[1] + '</p>');
		});
        */
    
    });

	
	/***********************
	* Colorbox
	************************/
	
	$(".cbox_gallery").colorbox(); 
	
	// hover opacity animate on ad images
	$(".images_thumbs a img").hover(
		function(e) {
			if( ! $(this).hasClass("fade") ) {
				$(this).animate({
					opacity:0.6				
				}, 300);
			}
		}, 
		function(e) {
			if( ! $(this).hasClass("fade") ) {
				$(this).animate({
					opacity:1.0				
				}, 300);
			}
		}
	);
	
	// change ad image when click on thumb
	$(".image_popup_thumb").click(function(){

		var img = $(this).find("img");
		if(img.hasClass("fade")) {
			return false;
		}
		
		var new_id = $(this).attr('alt');
		
		var new_image = img.attr("alt");
		var title = img.attr('title');
		// target
		var target = $('.images_main img').first();
		
		// remove fade class for everyone
		$(this).parent().find("img.fade").not(img).removeClass("fade");
		$(this).parent().find("img").not(img).animate({
			opacity:1.0		 
		}, 300);
		
		// add fade class to me
		img.addClass("fade"); 
		img.animate({
			opacity:0.6		 
		}, 300);
		
		// fade out large
		/*
		target.animate({
			opacity:0.6				
		}, 300);*/
		
		// switch image
		target.attr("src", new_image).attr('alt', new_id);

		// Fade in
		/*
		target.animate({
			opacity:1.0				
		}, 300);
		*/
		
		return false;
	
	});
	
	$('.show_all_images').click(function() {
		var url = $(this).attr('href');
		var id = $('img', this).attr('alt');
		if(id) {
			url += '#'+id;	
		}
		var atts = 'width=920,height=800,scrollbars=1,status=0,resizable=1,screenx=200,screeny=200';
		window.open(url, '_blank', atts);
		
		return false;		
	});
	
	
	
	/***********************
	* Login form functions
	***********************/
	
	// Show popup login form
	$("#show_login_form").click(function(){
		$("#screen_overlay").show();		
		$("#login_popup").show();	
		
	
	});
	
	// Close popup login form
	$("#close_popup").click(function(){
		$("#screen_overlay").hide();		
		$("#login_popup").hide();								 
	});
	
	// Close popup login form
	$("#close_popup").click(function(){
		$("#screen_overlay").hide();		
		$("#leads_popup").hide();								 
	});
	

	/***************
	* TOOLTIP
	***************/
	xOffset = 10;
	yOffset = 20;		
	// these 2 variable determine popup's distance from the cursor
	// you might want to adjust to get the right result			
	$(".tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    }, 
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
	
	/***************
	* TOOLTIP
	***************/
	xOffset = 10;
	yOffset = 20;		
	// these 2 variable determine popup's distance from the cursor
	// you might want to adjust to get the right result			
	$(".tooltip_link").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip_link'>"+ this.t +"</p>");
		$("#tooltip_link")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip_link").remove();
    });	
	$(".tooltip_link").mousemove(function(e){
		$("#tooltip_link")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});	
	
	/********************
	* Timeout functions
	********************/
	
	//Check if we have any notification, fadeout after 4 secs
	setTimeout(function () { $(".notification").fadeOut('slow');  }, 4000);
	
});

function isEmail(str) {
	return (str.lastIndexOf(".") > 2) && (str.indexOf("@") > 0) && (str.lastIndexOf(".") > (str.indexOf("@")+1));
}

