﻿
var networkId = 0;
var networkId2 = 0;
var networkNet = 2; //iGoogle
var addId = 0; //Unknown.

var ig_synd;
var ig_mode;
var ig_parent;
var ig_source;
var ig_isIGoogle = false;
var ig_isSyndicated = false;
var ig_isOpenSocial = false;

var ig_isCanvas = false;
var ig_isProfile = false;


var IGNETWORKID = "igid";
var IGNETWORKID2 = "igid2";
var IGNETWORKNET = "ignet";
var IGADDID = "igadd";


// Method to generate a random number
function getRandomNumber(minNumber, maxNumber) {
    var num = minNumber + Math.floor(Math.random() * (maxNumber - minNumber));
    return num;   
}
//Maybe increase chance of uncorrelated random ids.
var initialRandom = getRandomNumber(1, 2147483646);

function getNetworkId()
{
    return networkId;
}

function getNetworkId2()
{
    return networkId2;
}

function getNetwork()
{
    return networkNet;
}

function getAddId()
{
    return addId;
}

function setNetworkIds(id, id2)
{
    networkId = id;
    networkId2 = id2;
}

//_args[]
function getQueryValue(query, str) {
    var names = query.split("&");
    for (var i=0; i<names.length; i++) {
        var pair = names[i].split("=");
        if (pair.length > 1)
        {
            if (pair[0] == str) {
                return pair[1];
            }
        }
    }
    return "";
}

//synd=
// "hi5"  
// "orkut"  
// "ig"  
// "gd" Google Desktop
function parseSyndication(url)
{
    //iGoogle: http://166.gmodules.com/ig/ifr?url=http://dev-hotspots.shopathome.com/google/iFreeCoupons/iFreeCoupons.aspx&nocache=2147483647&ifpctok=1506272336495831331&up_igid=208823707&upt_igid=hidden&up_igid2=862021814&upt_igid2=hidden&lang=en&country=us&.lang=en&.country=us&synd=ig&mid=166&parent=http://www.google.com&extern_js=/extern_js/f/CgJlbhICdXMrMAo4ACwrMBA4ACwrMBI4ACwrMBM4ACw/-C5MBG2Eesg.js
    //iGoogle(synd=open): http://166.gmodules.com/ig/ifr?url=http://dev-hotspots.shopathome.com/google/iFreeCoupons/iFreeCoupons.aspx&nocache=2147483647&ifpctok=3490732004951559784&up_igid=208823707&upt_igid=hidden&up_igid2=862021814&upt_igid2=hidden&lang=en&country=us&.lang=en&.country=us&synd=open&mid=166&parent=http://www.google.com&extern_js=/extern_js/f/CgJlbhICdXMrMAY4ACwrMAo4ACwrMBA4ACwrMBI4ACwrMBM4ACw/xIuUmg3UimE.js
	//var OWNER  = document.location.hash.replace(/^.*gadgetOwner=(\d+).*$/, '$1');
	//var VIEWER = document.location.hash.replace(/^.*gadgetViewer=(\d+).*$/, '$1');

    try {
        ig_synd = getQueryValue(url, "synd");
        ig_mode = getQueryValue(url, "mode");
        ig_parent = getQueryValue(url, "parent");
        ig_source = getQueryValue(url, "source");
    }
    catch(e) {
        //alert("Exception: " + e);
    }
    if (ig_synd === "orkut" || ig_synd === "hi5")
    {
        ig_isOpenSocial = true;
    } else if (ig_synd === "ig" || ig_parent==="http://www.google.com") 
    {
        ig_isIGoogle = true;
    } else if (ig_synd == "open")
    {
        ig_isSyndicated = true;
    }
    
    if (ig_mode === "canvas") {
        ig_isCanvas = true;
    }
    if (ig_mode === "profile") {
        ig_isProfile = true;
    }
}


function getATargetFromPrefs()
{
    return '_top'; //'freecoupons'
    /*var aTarget= '_top'; //This page
    if (prefsGetString("linkTarget") === "new") {
        aTarget = 'freecoupons'; //'_blank';  //New Page
    }
    return aTarget;*/
}


function getATagFromTarget(link)
{
    var aTag = '<a href="' + link + '" target="';
    aTag += getATargetFromPrefs();
    aTag += '" >';
    return aTag;
}


// Display XML in HTML
function encodeXML(xmlstring) {
    var htmlstr = xmlstring.replace(/&/g, "&amp;");
    htmlstr = htmlstr.replace(/>/g, "&gt;");
    htmlstr = htmlstr.replace(/"/g, "&quot;");
    htmlstr = htmlstr.replace(/'/g, "&apos;");
    htmlstr = htmlstr.replace(/</g, "&lt;");
    return htmlstr;
}

function tabClicked() {
    adjustFrameHeight();
}

function submitAddToFavorites() {
    var favoritesurl = getAddToFavoritesUrl(getNetworkId(), getNetworkId2(), getNetwork(), getAddId());
    //alert(favoritesurl);
    window.open(favoritesurl, getATargetFromPrefs());
}

function clickFreeCoupons() {
    tabs.setSelectedTab(0);
}

function init() {
    //var searchString = prefsGetString("lastSearch");
    //_gel('searchForm').searchbox.value = searchString;
    
    //Load OpenSocial Content.  (Moved because not ready yet...  but we could put a div in separate than server stuff obviously...)
    //osRequest();
}




function loadNetworkId()
{
    networkId = prefsGetString(IGNETWORKID);
    networkId2 = prefsGetString(IGNETWORKID2);
    networkNet = prefsGetString(IGNETWORKNET);
    addId = prefsGetString(IGADDID);
    if (!networkId)
        networkId = 0;
    if (!networkId2)
        networkId2 = 0;
    if (!networkNet)
        networkNet = 2; //iGoogle
    if (!addId)
        addId = 0;

//Moved to server side
    //if (!networkId) {
    //    //Random #
    //    networkId = initialRandom;
    //    //Might be better to get second id after loading or something.
    //    networkId2 = getRandomNumber(1,2147483646);
    //    prefsSet(IGNETWORKID, networkId);
    //    prefsSet(IGNETWORKID2, networkId2);
    //}
}

function saveNetworkId()
{
    //Load Network ID from profile.
    var profileNetworkId;
    var profileNetworkId2;
    var profileNetworkNet;
    try {
        var profileNetworkId = _gel('NetworkId').innerHTML;
        var profileNetworkId2 = _gel('NetworkId2').innerHTML;
        var profileNetworkNet = _gel('NetworkNet').innerHTML;
    } 
    catch (e)
    {
    }
    //Did we find a server ID?
    if (profileNetworkId && profileNetworkId !== "0")
    {
        if (!profileNetworkId2)
            profileNetworkId2 = "0";
        if (!profileNetworkNet)
            profileNetworkNet = "2"; //google

        if (profileNetworkId !== networkId || profileNetworkId2 !== networkId2)
        {
            //Id from the server is different.  Save the new ID.
            networkId = profileNetworkId;
            networkId2 = profileNetworkId2;
            networkNet = profileNetworkNet;
            if (ig_isIGoogle)
            {
                prefsSet(IGNETWORKID, networkId);
                prefsSet(IGNETWORKID2, networkId2);            
                prefsSet(IGNETWORKNET, networkNet);            
                //alert("Saved New id = (" + networkId + "," + networkId2 + ") (" + ig_isIGoogle + ")");
            } else {
                //alert("Not saving New id = (" + networkId + "," + networkId2 + ") (" + ig_isIGoogle + ")");
            }
        }
    }
}



function doSearch(form) {
    var searchForm = document.getElementById('searchForm')	
    var input = searchForm.terms.value;    
    //var input = form.searchbox.value;    
    //prefsSet("lastSearch", input);

    //var url = "http://search.shopathome.com/sr.aspx?sf=";
    var url = getSearchUrl(encodeURIComponent(input), getNetworkId(), getNetworkId2(), getNetwork(), getAddId()); //2 - iGoogle
    //url += encodeURIComponent(input);
    //url += "&st=D&search=Go";
    //alert('gotSearchUrl');
    //fetchContent(url, processResponse);  
    window.open(url, getATargetFromPrefs());
    //alert('would have opened window:' + url);
    //alert("Browse to: " + url);
    //return false;
}


function doViewAllCoupons()
{
    var url = getSearchUrl("", getNetworkId(), getNetworkId2(), getNetwork(), getAddId()); //2 - iGoogle
    url += "&stores=0";
    window.open(url, getATargetFromPrefs());
}



function Set_Cookie( name, value, expires, path, domain, secure ) 
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );

  /*
  if the expires variable is set, make the correct 
  expires time, the current script below will set 
  it for x number of days, to make it for hours, 
  delete * 24, for minutes, delete * 60 * 24
  */
  if ( expires )
  {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
  ( ( path ) ? ";path=" + path : "" ) + 
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				


function testCookie()
{
    //alert(document.cookie);
    //var precookie = Get_Cookie('testfc1');
    //var cookiestatus = "testfc1 (" + precookie + ") -> (";
    //Set_Cookie( 'testfc1', 'The cookie exists!', 30, '/', '', '' );
    //var postcookie = Get_Cookie('testfc1');
    //cookiestatus += postcookie + ")";

    //var precookie = Get_Cookie('testfc1sah');
    //cookiestatus += "\n   testfc1sah (" + precookie + ") -> (";
    //Set_Cookie( 'testfc1sah', 'The cookie exists!', 30, '/', '.shopathome.com', '' );
    //var postcookie = Get_Cookie('testfc1sah');
    //cookiestatus += postcookie + ")";

    //precookie = Get_Cookie('testcheckid');
    //cookiestatus += "\n   testcheckid (" + precookie + ")";

    //precookie = Get_Cookie('testLastVisit');
    //cookiestatus += "\n   testcheckid (" + precookie + ")";
  
    //alert(cookiestatus);
}

