/*
*
*   Base Coinks prototype object
*   Contains common operations.
*   Extend other objects this way:
*   var MyClass = function() { }
*   MyClass.prototype = new CoinksBase();
*/

// extension to allow storing of unique ID in element ID. Uses ":" to separate:
// for example "id=my_button:12 class=my_buttons" $(this).pk() -> "12".
// if args "element" and "pk" provided then will find matching element.
 
jQuery.fn.pk = function(){

    var id_attr = $(this).attr("id");
    if(!id_attr) return null;
    return id_attr.split(":").pop();
}

jQuery.pk = function(element, id){

    if (element && id){
        return this('[id=' + element + ':' + id + ']');
    }
}

var CoinksBase = function(options) {
    var _this = this;
    _this.options = options == undefined ? new Object : options;
    _this.url_root = _this.options.url_root == undefined ? '' : _this.options.url_root;
}




/*
 * Runs console.log and fails silently if firebug not installed.
 */ 
CoinksBase.prototype.log = function(msg){
    try{
	    console.log(msg);		
    } catch(e){
        // 'console' is not available in this browser
        alert(msg);
    }
}

CoinksBase.prototype.updatePoints = function(){
    var url = '/ajax_update_points/';
    var callback = function(response){
        //console.log(response);
	    $('#acct_pts').text(response.my_points);
    }
    $.get(url, null, callback, "json");    
}

/*
Binds JSON data to member variables.
*/
CoinksBase.prototype.bindData = function(data){
    var _this = this;
    for (key in data){
	    var value = data[key];
	    if (value != null && value != undefined){
	        _this[key] = value;
	    }		
    }	 
}

/*
Displays offer confirmation
*/
CoinksBase.prototype.displayOffer = function(offer_id, callback){
	var _this = this;
	var url = _this.url_root + '/couponstar/' + offer_id + '/';
    $.get(url, null, callback, "html");
}

/*
Handles offer takeup
*/
CoinksBase.prototype.takeupOffer = function(offer_id, params, callback){
    // takes up offer
    var _this = this;
    
    var _callback = function(response){
        // handle JSON mangling
        var error = response.no_error == 'False' ? true : false;

        var message = response.msg;
        
        callback(message, error);
              
        if (!error){
            _this.updatePoints();
        }
    }

    var url = _this.url_root + '/couponstar/' + offer_id + "/";
    $.post(url, params, _callback, "json");
}

CoinksBase.prototype.isNumeric = function(str){
    //  check for valid numeric strings	
    var validChars = "0123456789";
    var length = str.length;
    if (length==0) return false;
    for (var i=0; i<length; i++){
	var chr = str.charAt(i);
	if (validChars.indexOf(chr) == -1){
	    return false;
	}
    } 	
    return true;
}
 


