var debug = false;
// Data class
var AjaxData = {
    defaultRequest: 'sites/updates/1',
    firstRequest: true,
    cacheMax:(window.CACHE_LIMIT != undefined ? window.CACHE_LIMIT : 5),
    cacheItems: [],
    cachePaths: [],
    checkCache: function(request) {
        if (request == this.defaultRequest && window.cache != undefined && window.cache['sites'] != undefined)
            return window.cache['sites'];

        for (i=0;i<this.cachePaths.length;i++) {
            if (this.cachePaths[i] == request)
                return this.cacheItems[i];
        }
        return false;
    },
    addCache: function(request, data) {
        // check if this request is cached first
        if (request == this.defaultRequest)
            return;
        for (i=0;i<this.cachePaths.length;i++) {
            if (this.cachePaths[i] == request)
                return;
        }

        // if we're at the max allowed number of cache items remove the earliest accessed
        if (!(this.cacheItems.length < this.cacheMax)) {
            this.cacheItems.shift();
            this.cachePaths.shift();
        }
        
        this.cacheItems.push(data);
        this.cachePaths.push(request);
    },

    // code to send the request to the server and pass through the result
    doAjaxRequest: function(request, callback) {
        var cache = this.checkCache(request);
        var ajax = new XMLHttpRequest();
        var thisObj = this;

        // if we already have the item for this request cached do not continue after passing to callback
        if (cache !== false) {
            callback(cache);
            return;
        }

        ajax.onreadystatechange = function() {
            if (ajax.readyState == 4) {
                if (debug) {
                    alert(ajax.responseText);
                }
                else {
                    //debug = true;
                    if (callback) {
                        //var obj = eval('(' + ajax.responseText + ')');
                        var obj = json_parse(ajax.responseText);

                        thisObj.addCache(request, obj);

                        if (callback)
                            callback(obj);

                        // if we have a Google Analytics tracker, count this as a new page hit
                        if (window.pageTracker) {
                            window.pageTracker._trackPageview();
                        }
                    }
                }

                // turn off the timeout -- we're done
                app.removeAjaxTimeout();
            }
        }

        var url = '' + document.location;
        
        // remove everything before the third / (removes the domain)
        var pos = 0;
        for (var count = 0; count < 3; ++count) {
            pos = url.indexOf('/', pos+1);
        }
        url = url.substr(pos);

        // url is now like /en/s7/pc/tour/?revid=1187&viewSpeed=450
        url = url.replace('/tour/', '/ajax/');

        // remove any # after the url
        if (url.indexOf('#') != -1) {
            url = url.substr(0, url.indexOf('#'));
        }

        // append proper query token
        if (url.indexOf('?') != -1) {
            url += '&';
        }
        else {
            url += '?';
        }

        // append request
        url += 'request=' + request;

        ajax.open("GET", url, true);
        ajax.send(null);

        // set a timeout to improve performance on low-end connections
        app.setAjaxTimeout(ajax, callback);
    },

    clickTrack: function(click) {
        var request = 'track/' + click;
        this.doAjaxRequest(request, null);
    },

    logVideoView: function(id, isTrailer) {
        var request = 'logVideoView/' + id + '/' + (isTrailer ? 0 : 1);
        this.doAjaxRequest(request, null);
    },

	getSiteName: function(shrt, callback) {
        var request = 'sitename/' + shrt;
        this.doAjaxRequest(request, callback);
	},

	/* 	example paths:	#support, #support/contact
		check if args contains anything after support/ if not, then pass back the menu html. if it does, check if its 
	   	a topic. if it is, passback the topic HTML and a fancy caption. e.g. topfaq == Top FAQ's */
	support: function(args, callback) {
        /*
		var htmlReturn = '';

		if (!args.length) htmlReturn = dummy.support.menu;
		else if (args[0] == 'contact') htmlReturn = dummy.support.contact;
		else htmlReturn = dummy.support.topic;

		var captionReturn = dummy.support.captions[args[0]] ? dummy.support.captions[args[0]] : (args.length ? 'Unknown Topic' : 'Support');
		if (callback) callback({html:htmlReturn, caption: captionReturn});
        */

        // support just links off to an existing page
        window.open('/?style=s4&action=support');
	},

    view: function(args, callback) {
        switch (args[0]) {
            case 'funnyclips': {
                this.doAjaxRequest('funnyclips', callback);
                break;
            }
            case 'premium': {
                this.doAjaxRequest('premiumServices', callback);
                break;
            }
            case 'bonusfeeds': {
                var searchStr = args[1] == undefined ? '' : args[1];
                this.doAjaxRequest('bonusfeeds/' + searchStr, callback);
                break;
            }
            default: {
                callback({error: 'That page does not exist.'});
            }
        }
    },
	
    extras: function(callback) {
        this.doAjaxRequest('extras', callback);
    },
	
    ringTones: function(callback) {
        this.doAjaxRequest('ringtones', callback);
    },
	
    wallPapers: function(callback) {
        this.doAjaxRequest('wallpapers', callback);
    },
	
    wallpaper: function(args, callback) {
        var id = args[1];
        this.doAjaxRequest('wallpaper/' + id, callback);
    },
	
    topRated: function(args, callback) {
		// args[0] = page (optional)
        var request = 'episodes/rating/' + app.getVideoSpeed() + '/all/' + this.findPageNum(args, 0);
        this.doAjaxRequest(request, callback);
        return;
	},

    stories: function(args, callback) {
		// args[0] = page (optional)
        var request = 'stories/' + this.findPageNum(args, 0);
        this.doAjaxRequest(request, callback);
        return;
    },

    story: function(args, callback) {
        var request = 'story/' + args;
        this.doAjaxRequest(request, callback);
        return;
    },
	
    sites: function(args, sortMethod, callback) {
        // args[0] = page (optional?)
        var request = 'sites/' + sortMethod + '/' + this.findPageNum(args, 0);
        this.doAjaxRequest(request, callback);
	},

	episodes: function(args, sortMethod, callback) {
		// args[0] = siteShort
		// args[1] = page (optional)
        var request = 'episodes/' + sortMethod + '/' + app.getVideoSpeed() + '/' + args[0] + '/' + this.findPageNum(args, 1);
        this.doAjaxRequest(request, callback);
	},

	stars: function(args, callback) {
		// args[0] = page (optional)
        var request = 'models/' + this.findPageNum(args, 0);
        this.doAjaxRequest(request, callback);
        return;
	},

	photos: function(episodeID, callback) {
        var request = 'photos/' + episodeID;
        this.doAjaxRequest(request, callback);
	},

	gallery: function(episodeID, callback) {
        var request = 'gallery/' + episodeID;
        this.doAjaxRequest(request, callback);
	},

	episode: function(episodeID, callback) {
        var request = 'episode/' + app.getVideoSpeed() + '/' + episodeID;
        this.doAjaxRequest(request, callback);
	},

	getFavStatus: function(episodeID, callback) {
        var request = 'isfavorite/' + episodeID;
        this.doAjaxRequest(request, callback);
	},

	deleteFav: function(episodeID, callback) {
        var request = 'removefav/' + episodeID;
        this.doAjaxRequest(request, callback);
	},

	addFav: function(episodeID, callback) {
        var request = 'addfav/' + episodeID;
        this.doAjaxRequest(request, callback);
	},

	favorites: function(args, callback) {
		// args[0] = page (optional)
        var request = 'favorites/' + this.findPageNum(args, 0) + '/' + app.getVideoSpeed();
        this.doAjaxRequest(request, callback);
	},

	search: function(args, sortMethod, callback) {
		// args[0] = search term
		// args[1] = page
        var request = 'search/' + sortMethod + '/' + app.getVideoSpeed() + '/' + args[0] + '/' + this.findPageNum(args, 1);
        this.doAjaxRequest(request, callback);
	},
	
	pornstarSearch: function(args, callback) {
		// args[0] = search term
		// args[1] = page
        var request = 'pornstarsearch/' + app.getVideoSpeed() + '/' + args[0] + '/' + this.findPageNum(args, 1);
        this.doAjaxRequest(request, callback);
	},	

	star: function(star, callback) {
        var request = 'modeldetail/' + star + '/' + app.getVideoSpeed();
        this.doAjaxRequest(request, callback);
	},
	
	liveshows: function(callback) {
        this.doAjaxRequest('liveshows/' + app.getVideoSpeed(), callback);
	},
	
	nudecelebsfeed: function(callback) {
        this.doAjaxRequest('nudecelebsfeed/' + app.getVideoSpeed(), callback);	
    },

    ratingUpdate: function( args ) {
		// args[0] = episode unique name
		// args[1] = rating value
    	var ajaxRate = new XMLHttpRequest();
    	var rateUrl = '/index.php?action=rateEpisode&uniqueName='+args[0]+'&rating='+args[1];
    	ajaxRate.open("GET", rateUrl, true);
    	ajaxRate.send(null);
    },

    // some utility functions

    // returns a page number, or 1
    findPageNum: function(argArray, position) {
        if (argArray.length <= position) {
            return 1;
        }
        else {
            return argArray[position];
        }
    }
};

