/*  Starry Set Form Widget
 *  (c) 2006 Chris Iufer <chris@duarte.com>
 *  Starry is freely distributable under the terms of an MIT-style license.
 *  See the Duarte Design web site: http://www.duarte.com/portfolio/
/*--------------------------------------------------------------------------*/
var debug = false;

var StarryDefaults = {
		sprite: "black_stars.gif",
		width: 20,
		height: 20,
		startAt: 0,
		maxLength: 5,
		multiplier: 1,
		showNull: true,
		align: 'left',
		feedback: false,
        formid: "formid",
        fsub: false
};

// The Starry Class
// new Starry('id_of_element'[, {options}]);
// This is the main starry widget. Create new widgets after window load
var Starry = Class.create();
Starry.prototype = {
	initialize: function(element) {
		this.element = $(element);
		this.element.className = "starry";				
		this.options = {};
		// get our defaults
		Object.extend(this.options, StarryDefaults);
		Object.extend(this.options, arguments[1] || {});		
		this.id = this.name = this.options.name || "starry" + id.next();
		if(debug) console.log(this.options.showNull);
		// lets build our array with an extra one for null
		this.children = new Array(this.options.maxLength + 1);
		if(debug) console.log('children length '+ this.children.length);		
		// lets make the hidden form value
		this.hidden = document.createElement("input");
		this.hidden.type = "hidden";
		this.hidden.name = this.name;
        this.hidden.id = this.id;
		this.element.appendChild(this.hidden);				
		// build out each child
		for(i=0; i < this.children.length; i++) {
			this.children[i] = new SingleStar(this, i);
			this.element.appendChild(this.children[i].element);
		}
		if( this.options.feedback ) {
			this.feedback = document.createElement('div');
			this.feedback.className = "feedback";
			this.feedback.style.cssFloat = this.feedback.style.styleFloat = this.options.align;
			this.element.appendChild(this.feedback);
		}	
		// startup
		this.selected = this.options.startAt;
		this.reset(this.selected);
	},
	set: function(index) {
		if(debug) console.log('set index '+ index);
		// set the child
		for(var i=1; i < this.children.length; i++) {
			this.children[i].element.style.backgroundPosition = (i <= index) ? "0 -" + this.options.height * 2 + "px" : "0 0";
        }
		if(this.options.feedback) { 
			this.feedback.innerHTML = this.children[index].value;
        }    
		this.selected = index;
		// set the form value
		this.hidden.value = this.children[index].value;
        if(this.options.fsub) { 
            this.options.fsub = false;
            rateform(this.hidden.value);
        }
        if(debug) console.log('set value ' + this.hidden.value);
	},
	show: function(index) {
		if(debug) console.log('show index '+ index);		
		// show the child
		for(var i=1; i < this.children.length; i++) {
			this.children[i].element.style.backgroundPosition = (i <= index) ? "0 -" + this.options.height + "px" : "0 0";
        }    
		if(this.options.feedback) {
			this.feedback.innerHTML = this.children[index].value;
        }	
	},
	reset: function() { this.set(this.selected); },
	clear: function() {
		for(var i=1; i < this.children.length; i++)
			this.children[i].element.style.backgroundPosition = "0 0";
	}
};

// Class: SingleStar(parent_object, index of that parent's children)
// Not to be called directly, inherits its options from a Starry object
var SingleStar = Class.create();
SingleStar.prototype = {
	initialize: function(parent, index) {
		this.parent = parent;
		this.index = index;
		if(debug) console.log('Creating star at index '+ this.index);
		this.value = this.index * this.parent.options.multiplier;
		if(debug) console.log('value '+ this.value);
		this.element = document.createElement("div");
		this.element.style.width = this.parent.options.width + "px";
		this.element.style.height = this.parent.options.height + "px";
		this.element.style.backgroundImage = "url(" + this.parent.options.sprite + ")";
		this.element.style.backgroundPosition = (this.index == 0) ? "0 -" + this.parent.options.height * 3  +"px" : "0 0";
		this.element.className = "standard_star";
		this.element.style.cssFloat = this.parent.options.align;
		if(!this.parent.options.showNull && this.index == 0) this.element.style.display = "none";
		this.element.onclick = function() { 
            this.parent.set(this.index); 
            this.parent.options.fsub=true; 
        }.bind(this);
		this.element.onmouseover = function() { this.parent.show(this.index); }.bind(this);
		this.element.onmouseout = this.parent.reset.bind(this.parent);
		if(debug) console.log('set onclick handler');
	}
};

// this function manages an auto_increment for id's
var id = { start: 0, prev: 0, next: function() { return this.start + this.prev++; } };

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
/**
 * This function returns the value of url string parameter
 * @param {String} which
 * @return {String}
 */
function urlpars(which) {
    var params = location.search;
    if (params.length==0) { return ""; }
    params = params.substr(1, params.length); // get rid of ?
    var pairs = params.split("&");
    for (var i=0; i<pairs.length; i++) {
        var pair_values = pairs[i].split("=");
        if (pair_values[0] == which) {
            return pair_values[1];
        }
    }
    return "";
}
/**
 * This function adds the star rating of the property to the cookie
 * @param {Number} starrating
 */
 
 var propAddCounter = 0;
 var propAddCounterStar = "";
function rateform(starrating) {
    if(starrating=="" || starrating == null || starrating == undefined) { return "";}
    var cname = "LIST"
    var clist = readCookie(cname);
    
    clist = unescape(clist);
    clist = clist.split(":::");
    var pid = urlpars("id");
    var str ="";
    var bExists = false;
    //alert (clist);
    //alert (pid);
    var flag = 1;
    for(var k=0;k<clist.length;k++) {
        /* now str[0] is the id of whatever house(s) */
        str = clist[k].split("~");
        var newstr = "";
        if(str[0] == pid) { // this property exists in the cookie, add the rating
            str[4] = "rating"+starrating;
            newstr = str.join("~");
            clist[k] = newstr;
            var cvalue = clist.join(":::");    
                cvalue = escape(cvalue);
            var cdate = new Date();
                cdate.setTime(cdate.getTime()+(7*24*60*60*1000));
            var expires = "; expires="+cdate.toGMTString();
            document.cookie = cname+"="+cvalue+expires+"; path=/";
            var frameurl = document.getElementById("viewmylist").src;
            frameurl = frameurl.split("?");
            if(window.frames) {
		//  alert('frames redirect');
                window.frames["viewmylist"].location.href=frameurl[0]+"?msg='Rating+Saved'";
            }      
            flag = 0;
            propAddCounter = 0;
            return false;
        } else {
          //alert("You need to add this property to your list before you can rate it");
        }  
    }
    
        if (flag == 1) {
                if (propID != "" && propAddCounter == 0) {
                        addtolist('add', propID,ntype, propAddress, 'true', propPhoto, '  <span class=\'addtolist\'>Property Added</span>', 'viewmylist', 'addto_list_div')
                        propAddCounter++;
                        propAddCounterStar = starrating;
                        return false;
                } else {
                        alert("You need to add this property to your list before you can rate it");
                }
        }
}

function extendedRating () {
        if (propAddCounterStar != "") {
                rateform(propAddCounterStar)
                propAddCounterStar = "";
        }
}