var search_request;
var loading = {};
var reviews = {};

window.addEvent("domready", function( ) {



	$$('.site').each(function(el) {
		new SlideGroup({
			'elements': el.getElements(".side-info")
		});
	});


	var form = $$('form.list_filter').pop();

	form.getElements('div.legend').each(function(leg, i) {
		var l = new Element("a", {
			'href': '#',
			'html': leg.get("html")
		});
		l.setStyle("visibility", "visible");
		leg.empty( );
		l.inject(leg);
	});
	
	/*form.addEvent("submit", function(ev) {
		updateSearch(this);
		new Event(ev).stop( );
	});*/
	
	var submit = form.getElement("input[type=submit]");
	if(submit) submit.dispose();

	var pp = new PrettyPanels({
		'panels': $$('fieldset'), 'triggers': $$('div.legend'), 'container': form,
		'initialPanel': 0, 'mode':'horizontal', 'squeeze': 0.001, 'showMorphs': [
			{'background-color': '#ffffff', 'opacity': 1},
			{'background-color': '#ffffff', 'opacity': 1},
			{'background-color': '#ffffff', 'opacity': 1},
			{'background-color': '#ffffff', 'opacity': 1}
		], 'hideMorph': {'opacity': 0.8, 'background-color': '#faf3f3'}
	});

	submit.inject(form.getParent(), "after");
	submit.addEvent("click", function(ev) { 
		//updateSearch(form);
		form.submit();
		new Event(ev).stop( );
	});

	$$('.site .more a').addEvent("click", function(ev) {
		new Event(ev).stop( );
		loadReview(this);
	});

    $$('.user-review').setStyle("display", "none");
    $$('.usersubmit').setStyle("display", "none");
    $$('.usersubmit input').addClass("withScript");
    $$('.ratings-button').addEvent("click", function(ev) {
        new Event(ev).stop( );
        this.getParent(".site").getElements(".user-review").setStyle("display", "");
    
        this.getParent(".userrate").setStyle("display", "none");
        this.getParent(".userrate").getPrevious(".usersubmit").setStyle("display", "block");
    });

    $$('form.siteForm').addEvent("submit", function(ev) {
        new Event(ev).stop( );
        this.getElements(".review .error-message").destroy( );
        this.getElements(".review .success-message").destroy( );

        var ratingEls = this.getElements("select.user-review"); 
        var hasMissing = false;
        ratingEls.each(function(el) {
            if(!el.get('value')) {
                el.tween('background-color', '#FCC');
                hasMissing = true;
            } else el.tween('background-color', '#CFC');
        });

        if(hasMissing) {
            var er = new Element("div", {'class': 'error-message', 
                'html': 'Please specify a rating for all categories before '+
                    'submitting.'});
            er.inject(this.getElement(".review"));
            er.highlight( );
        } else {
            var er = new Element("div", {'class': 'error-message submitting', 
                'html': 'Please wait whilst your ratings are submitted...'});
            er.inject(this.getElement(".review"));

            var r = this.retrieve('ratingRequest');
            if(r) r.cancel( );
            r = new Request.JSON({
                url: this.get('url'),
                method: this.get('method'),
                data: this.toQueryString( ),
                onComplete: function( ) {
                    this.getElements(".error-message").destroy( );
                }.bind(this),
                onSuccess: function(json, text) {                    
                    var er = new Element("div", {'class': 'success-message', 
                        'html': 'Thank you, your ratings have been submitted and '+
                        'will be reflected in the totals shortly.'});
                    er.inject(this.getElement(".review"));

                    this.getElement(".userrate").setStyle("display", "");
                    this.getElement(".usersubmit").setStyle("display", "none");   
                    this.getElements(".user-review").setStyle("display", "none");
                }.bind(this),
                onFailure: function(err) {
                    var er = new Element("div", {'class': 'error-message', 
                        'html': 'Sorry, your ratings could not be submitted. '+
                            'This may be a temporary issue, so please try again '+
                            'or contact support if the problem persists.'});
                    er.inject(this.getElement(".review"));
                }.bind(this)
            });
            r.send( );
            this.store('ratingRequest', r);
        }
    });

    /*$$('select.user-review').addEvent("change", function(ev) {
        var rqst = this.retrieve('updateRqst');
        if(rqst) rqst.cancel( );
        var d = {};
        d[this.get('name')] = this.get('value');

        rqst = new Request.JSON({
            url: review_value_uri,
            data: d,
            method: 'get',
            onSuccess: function( ) {
                this.tween('background-color', '#CFC');
            }.bind(this),
            onFailure: function( ) {
                alert("Sorry, your rating could not be submitted. Please try "+
                    "again, and if the problem persists, contact TGT support.");
            }
        });
        rqst.send( );
        this.store('updateRqst', rqst);
    });*/

    $$('.site a.info').addEvent("click", function(ev) {
        new Event(ev).stop( );
        var can_vote = this.get('rel') == 'True';
        var el = this.retrieve('infoBox');
        if(el) el.destroy( );
        el = new Element("div", {'class': 'infoBox'});
        el.set('html', '<h6>'+this.get('title')+'</h6>');
        if(!can_vote) {
            new Element('span', {'html': 'Only premium members may rate '+
                'sites. See the home page for more details.'}).inject(el);
        } else {
            new Element('span', {'html': 'Select a rating from the drop-down '+
                'boxes to rate this site. Overall ratings will update when you '+
                'refresh the page.'}).inject(el);
        }
        var pos = this.getPosition( );
        el.setStyle("top", pos.y - 4);
        el.setStyle("left", pos.x - 4);
        el.inject(document.body);
        this.store('infoBox', el);       

        el.addEvent("mouseleave", function(ev) {
            this.retrieve('infoBox').destroy( );
        }.bind(this));
        el.addEvent("click", function(ev) {
            this.retrieve('infoBox').destroy( );
        }.bind(this));
    });

});

function showReview(obj, js) {
	var review = obj.getParent( ).getPrevious("div.review");
	//var full;
	if(full = review.getElement("div.full")) full.dispose( );
	full = new Element("div", {
		"class": "full",
		"opacity": 0,
		"position": "absolute",
		"html": js.output
	});
	//$$('body').adopt(full);
	//review.getParent("div.summary").setStyle("overflow", "hidden");
	//var size = full.getSize( );
	//full.dispose( );
	//review.tween('height', (review.getSize( ).y + size.y) * 1.5);
	//full.setStyle('position', '');
	review.adopt(full);
	full.tween('opacity', 1);	
	/*(function ( ) {
		review.setStyle("height", "auto"); review.getParent("div.summary").setStyle("overflow", "");
	}).delay(500);*/
}

function hideReview(obj, parent) {
	var f = parent.getElement("div.full");
	if(f) {
	    f.tween('opacity', 0);
		(function ( ) {f.dispose( )}).delay(600);
	}
	//obj.set('html', 'View Full Review &raquo;');
}

function loadReview(obj) {
    console.log(obj);
	var link = obj.getParent(".more").getElement("input.ReadURL");
	var url = link.get('value');

	if(loading[url]) {
		if(loading[url].cancel) loading[url].cancel();
		obj.tween('opacity', 1);
		var p;
		if((p = obj.getParent( ).getPrevious("div.review"))) {
			hideReview(obj, p);
			loading[url] = null;
		}		
		return;
	} 

	obj.tween('opacity', 0);
	if(reviews[url]) {
		obj.tween('opacity', 1);
		loading[url] = true;
		showReview(obj, reviews[url]);	
		//obj.set('html', "&laquo; Return To Summary");
		return;
	}

	loading[url] = new Request.JSON({
		'onFailure': function( ) {
			obj.set('html', "Sorry, we couldn't load the review. Please Try Again &raquo;");
		},
		'onComplete': function( ) {
			obj.tween('opacity', 1);
		},
		'onSuccess': function(js) {
			reviews[url] = js;
			//obj.set('html', "&laquo; Return To Summary");
			showReview(obj, js);
		}
	}).get(url);	
}

function updateSearch(form) {
	if(search_request) search_request.cancel();
	
	search_request = new Request.JSON({
		'onComplete': function(obj, txt) { responseToHtml(obj.payload); }
	}).get(review_url);
}

function responseToHtml(obj) {
	var list = JSON.decode(obj.list);
	if(!list) throw Error("Cannot decode list object");

	list.each(function(el) {
		try {
			siteObjToHtml(el);
		} catch(ex) {
		
		}
	});
}

function siteObjToHtml(o) {
	var siteObj = new Element(
		"div", {
			"class": "site",
			"id": "site-"+o.fields.slug
		}
	);
	
	/*var basicObj = new Element("div", {"class": "basic"});
	var basedObj = new Element("div", {"class": "based-in "+*/
	
	console.log(siteObj);
}

