var Car = function() {
	this.interestedCars = {}
	
	this.params = {
		start: 0, 
		limit: 10,
        sortby : "brandTitle",
        dir : "asc"
	};
	
	var uriParams = Uri.gpnv(document.location.href);
	for(var i in uriParams) {
		this.setParam(uriParams[i][0], uriParams[i][1])
	}
}

Car.prototype.load = function() {
	var self = this;
    $('#search .submit').addClass('disabled');
    $('#car-list').html("<div class='searching'></div>");
    setCookie('searchUrl',document.location.href, '', '/');
    $('#paginator').empty();
    this.updateFindFields(this.params);
	$.ajax({
		url: "/_ajax/cars/index/get-vehicle/",
		data: this.params,
		dataType: 'json',
		type: 'get',
		success: function(response) {
            $('#search .submit').removeClass('disabled');
			var html = response.resultJs.html;
			var start = Number(response.resultJs.start);
			var limit = Number(response.resultJs.limit);
			var totalCount = Number(response.resultJs.totalCount);

			if (html != "") {
                $('#car-list').html(html);
            } else {
                $('#car-list').html("<div class='notFound'>No vehicles found.</div>");
            }

			var paginator = '';
			if (Number(self.params.limit) < totalCount) {
				var pages = Math.ceil(totalCount/self.params.limit);
				var pageCurrent = Math.floor(self.params.start/self.params.limit);
				if (pages > 0) {
					if (pageCurrent > 0) {
						paginator += '<a href="#list" class="prev"><span class="ulined">Previous</span></a> | ';
					}
					for (var i = 0; i < pages; i++) {
						if (i != pageCurrent) {
							paginator += '<a href="#list" class="page-number" page="' + i + '">' + (i + 1) + '</a>';
						} else {
							paginator += '<a class="page-current" >' + (i + 1) + '</a>';
						}
						if (i != pages - 1) {
							paginator += ' | ';
						}
					}
					if (pageCurrent != pages - 1) {
						paginator += '| <a href="#list" class="next"><span class="ulined">Next</span></a>';
					}
				} 
			}
			$('#paginator').html(paginator);
			self.updateInterestedCars();
        }
	});	
}
Car.prototype.featured = function() {
	var self = this;
	$.ajax({
		url: "/_ajax/cars/index/get-featured/",
		data: { featured:1 },
		dataType: 'json',
		type: 'get',
		success: function(response) {
			var html = response.resultJs.html;
            
            if (html != "" && html) {
                $('#car-featured').html(html);
            } else {
                $('#rightCol .cars').remove();
            }

			self.updateInterestedCars();
		}
	});	
}
Car.prototype.similar = function() {
	var self = this;
	$.ajax({
		url: "/_ajax/cars/index/get-similar/",
		data: { currentCarBrandId:currentCarBrandId, currentCarId:currentCarId },
		dataType: 'json',
		type: 'get',
		success: function(response) {
    		var html = response.resultJs.html;
        if(html != ''){
            $('#car-similar').html(html);
        } else {
            $('#car-similar').remove();
        }
		}
	});	
}
Car.prototype.req = function() {
	var self = this;
	$('#rightCol .cars .requestMoreInfo .sendReq').addClass('disabled');
	$.ajax({
		url: "/_ajax/cars/index/get-req/",
		data: { 
			carSendReqId:$('#carSendReqId').val() ,
			carSendReqName:$('#carSendReqName').val() ,
			carSendReqPhone:$('#carSendReqPhone').val() ,
			carSendReqEmail:$('#carSendReqEmail').val() ,
			carSendReqEText:$('#carSendReqEText').val()  
		},
		dataType: 'json',
		type: 'get',
		success: function(response) {
            $('#rightCol .cars .requestMoreInfo')[0].reset();
            $('#rightCol .cars .requestMoreInfo .sendReq').removeClass('disabled');
            var html = response.resultJs.html;
            $('.requestMoreInfo .statMessage').remove();
			$('.requestMoreInfo').append('<div class="statMessage">'+html+'</div>');
            $('#interestedCars').empty();
            setTimeout(function() {
                $('.requestMoreInfo .statMessage').remove();
            }, 5000);
            //html('<div class="header"></div><div class="statMessage">'+html+'</div>');
//			self.updateInterestedCars();
		}
	});	
}


Car.prototype.setParam = function(name, value) {
    if (name && value && value!="0" && value!="") {
        this.params[name] = value;
        Uri.set(name, value);
    } else if (name) {
        Uri.remove(name);
        this.params[name] = 0;
    }
}

Car.prototype.loadOnSelectChange = function(name, value) {
    this.setParam(name, value);
    Uri.remove('start');
    this.params['start'] = 0;
    if(currentURLconst.pathname=='/inventory/') {
        this.load();
    } else {
        document.location.href = '/inventory/' + document.location.hash;
    }
}

Car.prototype.getParam = function(name) {
	return this.params[name];
}

Car.prototype.updateFindFields = function(params) {
    for (var key in params) {
        if ($('#search #'+key).is('select')) {
            $('#search #'+key).find('option[value='+unescape(params[key])+']').attr('selected','selected');
        }
    }
    if (params['brandId']) {
        $('#modelId').empty();
		$('#modelId').append( $('<option value="0">All models</option>') );
		for(var i in models) {
			if (models[i].carBrandId == params['brandId']) {
				$('#modelId').append( $('<option value="' + models[i].modelId + '">' + models[i].modelTitle + '</option>') );
			}
		}
        if (params['modelId'] && params['modelId']!=0) {
            $('#search #modelId').find('option[value='+params["modelId"]+']').attr('selected','selected');
        }
    }
    if (params['limit']) {
        $('#rightCol .cars .carsPerPage li a[limit='+params['limit']+']').addClass("active");
    }
    if (params['sortby']) {
        if (params['dir'] == "desc") {
            $('#rightCol .cars .sortby li a[sortby='+params['sortby']+']').addClass("desc");
        } else {
            $('#rightCol .cars .sortby li a[sortby='+params['sortby']+']').addClass("asc");
        }
    }

}

Car.prototype.updateInterestedCars = function() {
	
	var self = this;
	
	$('#interestedCars').empty();
	var carSendReq='';
	for(var id in this.interestedCars) {
		if (this.interestedCars[id]) {
			$('#interestedCars').append($('<div><input type="checkbox" name="cars[][' + id + ']" carId="' + id + '" checked> &nbsp; <label>' + this.interestedCars[id] + '</label></div>'));
			if(carSendReq!=''){ carSendReq+='-'; }
			carSendReq+=id;
		}
	}
	$('#carSendReqId').val(carSendReq);
	
	$('.interested input').each(function(){
		if ($(this).attr('carId')) {
			var carId = $(this).attr('carId');
			if (self.interestedCars[carId] && self.interestedCars[carId] != '') {
				$(this).attr('checked', true);
			} else {
				$(this).attr('checked', false);
			}
		}
	})
	
}


Car.prototype.addInterestedCar = function(carId, title) {
	this.interestedCars[carId] = title;
}


Car.prototype.removeInterestedCar = function(carId) {
	this.interestedCars[carId] = undefined;
}

/** 
*
* Url parser
*
*/
function URL(url) {
    url = url || "";
    this.parse(url);
}
URL.prototype = {
    // Если меняем this.href, не забываем вызывать после этого this.parse()
    href: "",
    // Если меняем что-то из следующего, не забываем вызывать после этого this.update()
    protocol: "",
    host: "",
    hostname: "",
    port: "",
    pathname: "",
    search: "",
    hash: "",
    
    parse: function(url) {
        url = url || this.href;
        var pattern = "^(([^:/\\?#]+):)?(//(([^:/\\?#]*)(?::([^/\\?#]*))?))?([^\\?#]*)(\\?([^#]*))?(#(.*))?$";
        var rx = new RegExp(pattern); 
        var parts = rx.exec(url);
        
        this.href = parts[0] || "";
        this.protocol = parts[1] || "";
        this.host = parts[4] || "";
        this.hostname = parts[5] || "";
        this.port = parts[6] || "";
        this.pathname = parts[7] || "/";
        this.search = parts[8] || "";
        this.hash = parts[10] || "";
        
        this.update();
    },
    
    update: function() {
        // Плюшка для protocol - если не указан, берём текущий
        if (!this.protocol)
            this.protocol = window.location.protocol;
        
        // Плюшки для relative pathname/URL - если задаём relative, то "добавляется" к текущему
        this.pathname = this.pathname.replace(/^\s*/g, '');
        if (!this.host && this.pathname && !/^\//.test(this.pathname)) {
            // Если честно, это не лучший вариант. Но тут лучше я не придумал.
            var _p = window.location.pathname.split('/');
            _p[_p.length - 1] = this.pathname;
            this.pathname = _p.join('/');
        };
        
        // Плюшка для hostname - если не указан, берём текущий
        if (!this.hostname)
            this.hostname = window.location.hostname;
        
        this.host = this.hostname + (("" + this.port) ? ":" + this.port : "");
        this.href = this.protocol + '//' + this.host + this.pathname + this.search + this.hash;
    }
}

var currentURLconst = new URL(window.location.href);

Uri = {
    reserved : {
        byCategory : {
            'dir' : new Array('asc','desc')
        },
        byWordName : {}
    },
    getReservedByWords: function() {
        for (var cat in this.reserved.byCategory) {
            for (var i in this.reserved.byCategory[cat]) {
                this.reserved.byWordName[this.reserved.byCategory[cat][i]] = cat;
            }
        }
    },
    get: function(name) {
        var vars = [], hash;
        if (document.location.href.split("#")[1]) {
            var hashes = document.location.href.split("#")[1].split("/");
        } else {
            hashes = "";
        }
        
        for (var i=0;i<hashes.length;i++) {
            if (hashes[i] !='') {
                if (hashes[i] in this.reserved.byWordName) {
                    vars.push(this.reserved.byWordName[hashes[i]]);
                    vars[this.reserved.byWordName[hashes[i]]] = hashes[i];
                } else {
                    vars.push(hashes[i]);
                    vars[hashes[i]] = hashes[i+1];
                    i++;
                }
            }
        }
        
        if(name){
            return vars[name];        
	  	} else {
	  		return vars;
	  	}
    },
    set: function(name, value){
        var hash = (document.location.hash.split("#").length > 1) ? document.location.hash.split("#")[1] : "";
        
        if (this.get(name) == null) {
        if (name in this.reserved.byCategory) { 
            var pair = value;
        } else {
            var pair = name + "/" + value;
        }
            
            if (hash.length == 0) 
                hash = "/" + pair;
            else {
                if (hash.substring(hash.length - 1, hash.length) == '/') 
                    hash += pair;
                else 
                    hash += "/" + pair;
            }
        }
        else {
            var arr = this.gpn();
            var result = "";
            
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] != name) {
                    if (arr[i] in this.reserved.byCategory) {
                       result += "/" + this.get(arr[i]);
                    } else {
                       result += "/" + arr[i]+ "/" + this.get(arr[i]);
                    }
                } else {
                    if (name in this.reserved.byCategory) {
                       result += "/" + value
                    } else {
                       result += "/" + name + "/" + value;
                    }
                }
            }
            
            hash = result;
        }
        document.location.replace(document.location.href.split("#")[0] + "#" + hash + "/");
    },
    remove: function(name){
        if (this.get(name) == null) 
            return;
        var arr = this.gpn();
        var result = "";
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] != name) {
                if (arr[i] in this.reserved.byCategory) {
                   result += "/" + this.get(arr[i]);
                } else {
                   result += "/" + arr[i]+ "/" + this.get(arr[i]);
                }
            }
        }
        document.location.replace(document.location.href.split("#")[0] + "#" + result + "/");
    },
    gpn: function(href){
        href = href || window.location.hash;
        var params = new Array();
        if (href.split("#")[1]) {
            var hashes = href.split("#")[1].split("/");
        } else {
            var hashes = [];
        }
        for (var i=0;i<hashes.length;i++) {
            if (hashes[i] !='') {
                if (hashes[i] in this.reserved.byWordName) {
                    params.push(this.reserved.byWordName[hashes[i]]);
                } else {
                    params.push(hashes[i]);
                    i++;
                }
            }
        }
        return params;
    },
    gpnv: function(){
        var oString = new Array();
        var values = new Array();
        values = this.gpn();
        for (var i = 0; i < values.length; i++) {
            oString[i] = new Array(i);
            oString[i, i] = [values[i], this.get(values[i])];
        }
        return oString;
    }
}

Uri.getReservedByWords();
