jQuery.fn.handleRating = function(){
    if(this.size() > 0){
        var currentRate = Math.round(this.children("span.current").text());  
        var ratingStars = this.find("a img");
        var getRateValue = function(obj){
            var href = $(obj).parent().attr("href");
            return href.substr(href.indexOf("rate=")+5, href.length);
        };
        var ratingOver = function(obj){
            obj.parent().addClass("anc-hover"); 
            ratingStars.each(function(){
                if(getRateValue($(this)) <= getRateValue($(obj))){
                    $(this).attr("src", "/ui/img/rate-blue.png");    
                }
            });        
        };
        var ratingOut = function(obj){
            ratingStars.each(function(){
                if(getRateValue($(this)) <= currentRate){
                    $(this).attr("src", "/ui/img/rate-blue.png");    
                }
            });        
        };
        
        ratingOut();
        
        ratingStars.hover(
            function(){
                ratingStars.attr("src", "/ui/img/rate-grey.png");
                ratingOver($(this));
            },
            function(){
                ratingStars.attr("src", "/ui/img/rate-grey.png");
                ratingOut($(this));  
            }
        );
    }
};
jQuery.fn.initRateClick = function(){
    if(this.size() > 0){
        this.click(function(){
            $("li#rate").load($(this).attr("href") + " li#rate > span, li#rate span.current,li#rate div", function (responseText, textStatus, XMLHttpRequest) {
                $("li#rate").handleRating();
                $("li#rate a").initRateClick();
                }
            );
            
            return false;
       });           
    }   
};
var parseUri = {
	options: {
		strictMode: true,
		key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
			loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
		}
	},
	parseUri: function(value) {
		var o = parseUri.options,
			m = o.parser[o.strictMode ? "strict" : "loose"].exec(value),
			uri = {},
			i = 14;
		while(i--) {
			uri[o.key[i]] = m[i] || "";
		}
		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function($0, $1, $2) {
			if($1) {
				uri[o.q.name][$1] = $2;
			}
		});
		return uri;
	}
};
jQuery.fn.handleLinks = function() {
	$(this).find("a").each(function() {
		var href = $(this).attr("href");
		if(href) {
			var hrefHost = parseUri.parseUri(href).host;
			if(hrefHost !== "" && hrefHost != document.location.hostname && hrefHost != "www." + document.location.hostname && hrefHost != document.location.hostname.replace("www.", "")) {
				$(this).attr("target", "_blank");
			}
		}
	});
	return this;
};
jQuery.fn.handleTitle = function(){
	if(this.size() > 0){
		if(this.attr("title").length > 0){
			var title = this.attr("title");
			this.val(title);
		
			this.focus(function() {
				$(this).val("");
			});
			this.blur(function() {
				if($(this).val() == ""){
					$(this).val(title);
				}
			});
		}
	}
};
    
jQuery.fn.buttonStates = function(over, out){
    if(this.size() > 0){
        var image = this.children("img");
        this.hover(function(){
            $(this).addClass("anc-hover");
            image.attr("src",over);
        },function(){
            $(this).removeClass("anc-hover"); 
            image.attr("src",out);    
        });    
    }        
};
jQuery.fn.handleReportWidget = function(){
    if(this.size() > 0){
        href = this.attr("href");
        this.click(function(){
            $("#report").load(href + " #report-response span");
            return false; 
        });
        
    }        
};
jQuery.fn.handleWidgetListPaging = function(){
    if(this.size() > 0){
        this.click(function(){
            href = $(this).attr("href");
            $("#gallery-widgets").load(href + " #gallery-filter,#widget-search,.widget-list, #paging", function (responseText, textStatus, XMLHttpRequest) {                                            
                $("#paging a").handleWidgetListPaging(); 
                }
            );
            return false; 
        });
        
    }        
};
jQuery.fn.renderFormFromUl = function(){
	if($(this).size()>0){
		// Create elements
		var form = $(document.createElement("form"));
		var fieldset = $(document.createElement("fieldset"));
		var label = $(document.createElement("label"));
		var span = $(document.createElement("span"));
		var selElm = $(document.createElement("select"));
		var firstOptionElm = document.createElement("option");
		var button = $(document.createElement("button"));
		var buttonImage = $(document.createElement("img"));
		
		span.text("Please select a language");
		label.append(span);

		// Append first option
		$(firstOptionElm).attr("value", "-1").append(span.text()).appendTo(selElm);
		
		selElm.attr({"name":"market", "id":"market"});

		// Loop through links in ul
		this.find("a").each(function(){
			// Create option
			var optElm  = $(document.createElement("option"));
			// Add attributes and append to select
			optElm.attr("value", $(this).attr("href").substr($(this).attr("href").length-2,$(this).attr("href").length));
			optElm.text($(this).text());
			optElm.appendTo(selElm);
		});
		
        $(selElm).change(function(){
            form.submit();                    
        });
		
		label.append(selElm);
		fieldset.append(label);
		fieldset.append(button);
		form.append(fieldset);
		form.attr({"action":"/", "method":"get","class":"selectable"});
		$(this).before(form);
		$(this).remove();
	}
};
jQuery.fn.handleMarketSelector = function(){
    if($(this).size()>0){
        var form = $("#country-selector"); 
        $(this).change(function(){
            form.submit();                    
        });
    }
};
jQuery.fn.handleMinHeight = function(){
	if(this.size() > 0){
		var height = $(window).height() - ($("#header").height() + $("#footer").height());
		$(this).css("min-height", height);
	}
};
/* Load */
$(document).ready(function(){
    $("body").addClass("js");
	$(".selectable").renderFormFromUl();
    $("li#rate").handleRating();
    $("li#rate a").initRateClick();
    $(".embed input").click(function(){
        this.select();  
    });
    $("#create-widget a").buttonStates(button.CreateNewWidgetOff, button.CreateNewWidgetOn);
    $("a.to-gallery").buttonStates(button.WidgetGalleryOn, button.WidgetGalleryOff);
    $("a.the-competition").buttonStates(button.TheCompetitionOn, button.TheCompetitionOff);
    $(".ovi-store .footer a").buttonStates(button.VisistOviStoreOn, button.VisistOviStoreOff);
    $("#screen-saver-osx").buttonStates(button.MacOsXOn, button.MacOsXOff);
    $("#screen-saver-win").buttonStates(button.WindowsOn, button.WindowsOff);
    $("#back-to-gallery").buttonStates(button.BackToGalleryOn, button.BackToGalleryOff);
    $("#report-widget").handleReportWidget();
	$("#search-field").handleTitle();
	$("body").handleLinks();
    $("#country-selector select").handleMarketSelector();
    /*$("#paging a").handleWidgetListPaging(); */
    
	/*$("body.marketselector #content").handleMinHeight();*/
});
