/*global $ document escape unescape Image*/

function doOnloadActions(vertical)
{

}

function loadFromAdServer() {
    
    $.get($('#adserver img').attr('alt'), function(data) {
        $('#adserver').html(data);
    });
    
}

function pingAdServerURLs(vertical)
{
    var anchorArray = [],
        ix, tempAnchor,
        workingString,
        adClickURLs = [],
        jqxhr,
        jqField;
        
    // Extract all img URL refs containing ad-server params from DOM
    anchorArray = document.getElementsByTagName("a");
    for (ix = 0; ix < anchorArray.length; ix++) {
        tempAnchor = anchorArray[ix];
        if (tempAnchor.href.indexOf('MOB.ENTERTAINMENT.CITYSEARCH') !== -1 &&
            tempAnchor.href.indexOf('ADCLICK') !== -1) {
            workingString = tempAnchor.href.replace(/ADCLICK/, 'iserver');
            adClickURLs.push(workingString);
        }
    }
    
    // Ping each URL in the list of ad-server images
    for (ix = 0; ix < adClickURLs.length; ix++) {
        jqxhr = $.ajax(adClickURLs[ix], {crossDomain: true});
    }
    
}


function setArrayCookie(c_name,array) 
{
    var itemList = [],
        cookie = this.csm_getCookie(c_name),
        itemExists,
        arrIx, itmIx;
    
    if (cookie) {
        itemList = cookie.split('^');
    }
    
    if (typeof(array) === 'string') {
        array = array.split();
    }
    
    for (arrIx=0; arrIx < array.length; arrIx++) {
        itemExists = false;
        for (itmIx=0; itmIx < itemList.length; itmIx++) {
            if (itemList[itmIx] === array[arrIx]) {
                itemExists = true;
                break;
            }
        }
        if (!itemExists) {
            itemList.push(array[arrIx]);
        }
    }

    cookie = itemList.join('^');
    this.csm_setCookie(c_name,cookie,365);
}

function delArrayCookie(c_name,array) 
{
    var itemList = [],
        cookie = this.csm_getCookie(c_name),
        arrIx, itmIx;
    
    if (cookie) {
        itemList = cookie.split('^');
    }
    
    
    if (typeof(array) === 'string') {
        array = array.split();
    }
    
    for (arrIx=0; arrIx < array.length; arrIx++) {
        for (itmIx=0; itmIx < itemList.length; itmIx++) {
            if (itemList[itmIx] === array[arrIx]) {
                itemList.splice(itmIx,1);
                break;
            }
        }
    }
    cookie = itemList.join('^');
    this.csm_setCookie(c_name,cookie,365);
}
    
function cinemaAction(action)
{
    var inputs = document.getElementsByTagName("input"),
        inIx, cnIx, workingString, cState,
        cinemas = [], check,
        tempArray = [],
        workingState,
        cinemaList = this.getCookie('CINEMAS');
        
    for (inIx=0; inIx < inputs.length; inIx++)
    {
        if (inputs[inIx].getAttribute('type') === 'hidden') {
           workingState = inputs[inIx].getAttribute('name');
        }
        if (inputs[inIx].checked === true)
        {
            workingString = inputs[inIx].getAttribute('name');
            if (action === 'add') {
                if (cinemaList) {
                    if (cinemaList.indexOf(workingString) === -1) {
                        cinemas.push(workingString);
                    } 
                } else {
                    cinemas.push(workingString);
                }
            } else {
                cinemas.push(workingString);
            }
        }
    }
    if (action === 'add') {
        if (cinemas[0]) {
            if (cinemaList) {
                cState = cinemaList.indexOf(workingState);
                if (cState !== -1) {
                    cState = cinemaList.indexOf("^",cState);
                    workingString = cinemaList.substr(0,cState) + "^" + cinemas.join('^') + cinemaList.substr(cState);
                } else {
                    workingString = cinemaList + "^" + workingState + "^" + cinemas.join('^');   
                }
                this.csm_setCookie('CINEMAS',"",0);
            } else {
                workingString = workingState + "^" + cinemas.join('^');   
            }
            this.csm_setCookie('CINEMAS',workingString,365);
        }
        this.getCinemasForURLParam('cinema&sfilter=addConfirm');
    }
    if (action === 'remove') {
        if (cinemas[0]) {
            if (cinemaList) {
                for (inIx=0; inIx < cinemas.length; inIx++) {
                    cinemaList = cinemaList.replace("^"+cinemas[inIx],"");
                }
            }
        }
        tempArray = cinemaList.split("^");
        for (inIx=0; inIx < tempArray.length; inIx++) {
            if (tempArray[inIx].charAt(0) === ":") {
                if (inIx === tempArray.length-1) {
                    tempArray.splice(inIx,1);
                } else if (tempArray[inIx+1].charAt(0) === ":") { 
                    tempArray.splice(inIx,1);
                    inIx--;
                }                
            }
        }
        workingString = tempArray.join("^");
        this.csm_setCookie('CINEMAS',workingString,365);
        this.getCinemasForURLParam('cinema&sfilter=removeConfirm');
    }
}

//formats cookies as: ":provider^channel^channel^:provider^channel etc
function saveChannels()
{
    var inputs = document.getElementsByTagName("input"),
        inIx, chanIx,
        cookie, state,
        channelExists,
        channelString,
        channels = [];
        
    for (inIx=0; inIx < inputs.length; inIx++)
    {
       if (inputs[inIx].getAttribute('type') === 'hidden')
       {
           if (inputs[inIx+1].getAttribute('type') !== 'hidden') {
               channelExists = false;
               for (chanIx=0; chanIx < channels.length; chanIx++) {
                   if (channels[chanIx] === inputs[inIx].getAttribute('name')) {
                       channelExists = true;
                       break;
                   }
               }
               if (!channelExists) {
                   channels.push(inputs[inIx].getAttribute('name'));
               }
           }
       }
       if (inputs[inIx].checked === true)
       {
           channels.push(inputs[inIx].getAttribute('name'));
       }
    }
    
    cookie = this.csm_getCookie('CHANNELS');
    if (cookie) {
       this.csm_setCookie('CHANNELS',"",0);
    }
    this.setArrayCookie('CHANNELS',channels);
    channelString = channels.join('^');
    state = this.csm_getCookie('STATE');
    if (state) {
        document.location.search = 'state=' + state + '&browse=setup&tvPrefs=' + escape(channelString) + '&sfilter=savePrefs';
    } else {
        this.goToSelectState();
    }
}

function getChannels(redirect)
{
    var channels = this.csm_getCookie('CHANNELS'),
        state = this.csm_getCookie('STATE');
        
    if (state) {
        if (channels) {
            channels = encodeURIComponent(channels).replace( /\+/g, "%2B" );
        } else {
            channels = "";
        }
        if (redirect === 'channel') {
            document.location.search = 'state=' + state + '&browse=channel&tvPrefs=' + channels;
        }
        if (redirect === 'time') {
            document.location.search = 'state=' + state + '&browse=time&tvPrefs=' + channels;
        }
        if (redirect === 'tonight') {
            document.location.search = 'state=' + state + '&browse=time&pfilter=today&sfilter=primetime&tvPrefs=' + channels;
        }
        if (redirect === 'setup') {
            document.location.search = 'state=' + state + '&browse=setup&tvPrefs=' + channels;
        }
        if (redirect === 'search') {
            document.location.search = 'state=' + state + '&browse=search&tvPrefs=' + channels;
        }
    }
    else {
        this.goToSelectState();
    }
}

function favouriteAction(c_name, id, action, vertical) 
{
    if (action === 'add') {
        this.setArrayCookie(c_name, id);
        this.getFavouritesForURLParam(vertical,'addConfirm');
    }
    if (action === 'remove') {
        this.delArrayCookie(c_name, id);
        this.getFavouritesForURLParam(vertical,'removeConfirm');
    }
}

function goToVertical(vertical)
{
    var url = vertical + "index?state=",
        state = this.csm_getCookie('STATE');
    if (state) {
        url += state;
    }
    document.location = url;
}

function csm_getCookie(c_name)
{
   var i,x,y,ARRcookies=document.cookie.split(";");
   for (i=0;i<ARRcookies.length;i++)
   {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x===c_name)
      {
           return unescape(y);
      }
   }
}

function csm_setCookie(c_name,value)
{
    var exdays = 365, //default value
        exdate=new Date(),
        c_value;
    exdate.setDate(exdate.getDate() + exdays);
    c_value=escape(value).replace( /\+/g, "%2B" ) + ((exdays===null) ? "" : "; expires="+exdate.toUTCString()) + "; path=\"/\"";
    document.cookie=c_name + "=" + c_value;
}

function getCinemasForURLParam(browse, action, cinema, cState) {
    var state = this.csm_getCookie('STATE'),
        cinemas,
        params = "",
        browseArg = "";
        
    if (cState) {
        state = cState;   
    }
    
    if (state) {
        cinemas = this.csm_getCookie('CINEMAS');
        
        if(browse) {
            browseArg = "&browse=" + browse;
        }
            
        if(cinemas) {
            params += "state=" + state + browseArg + "&cinemas=" + cinemas;
        } else {
            params += "state=" + state + browseArg;
        }
        if (cinema) {
            params += "&pfilter=" + cinema;   
        }
        if (action) {
            params += "&gfilter=" + action;
        }
        document.location.search = params;    
    }
    else {
        this.goToSelectState();
    }
}

function getCinemasForURLQueryString(queryString) {
    var state = this.csm_getCookie('STATE'),
        cinemas = this.csm_getCookie('CINEMAS');
    if (state) {
        
        if(cinemas) {
            queryString += "&cinemas=" + cinemas;
        }    
        document.location.search = queryString;    
    }
    else {
        this.goToSelectState();
    }
}

function getFavouritesForURLParam(vertical, action) {
    var state = this.csm_getCookie('STATE'),
        faves = "",
        params = "";
        
    if (state) {
        if(vertical === 'restaurants') {
            faves = this.csm_getCookie('REST_FAV');
        }
        if (vertical === 'bars') {
          faves = this.csm_getCookie('BARS_FAV');
        }
        if (faves) {
            params += "state=" + state + "&browse=favourites&fav=" + faves;
        }
        else {
            params += "state=" + state + "&browse=favourites";
        }
        if (action) {
            params += "&sfilter=" + action;   
        }
        document.location.search = params;
    }
    else {
        this.goToSelectState();
    }
}

function favCheckForInfoPage(path, id, vertical) {
    var cookie,
        toPath = path;

    if (vertical === 'restaurants') {
        cookie = this.csm_getCookie('REST_FAV');
    }
    if (vertical === 'bars') {
        cookie = this.csm_getCookie('BARS_FAV');
    }

    if (cookie && cookie.indexOf(id) !== -1 ) {
        toPath += "&fav=yes";
    }
    document.location = toPath;
}

function doKeywordSearch() {
    var inputs = document.getElementsByTagName("input"),
        inIx, term,
        state,
        channels;
    
    for (inIx=0; inIx < inputs.length; inIx++)
    {
        if (inputs[inIx].getAttribute('name') === 'input') {
            term = inputs[inIx].value;
        }
    }
    
    state = this.csm_getCookie('STATE');
    if (state) {
        channels = this.csm_getCookie('CHANNELS');
        if (channels) {
        } else {
            channels = "";
        }
        document.location.search = 'state=' + state + '&browse=search&kws_search=' + term + '&tvPrefs=' + channels;
    }
    else {
        this.goToSelectState();
    }
}

function goToSelectState() {
    document.location.search = 'state=';
}

