var sw_embedded=0;  // by default sw is not embedded in another site.


// Array to hold map data
var aMapData=new Array();

var sw = new Object();
var gsaRequestLoader;
var tabViews = new Object();


function blankSearchBox(ele, text){
    if (ele.value==text) {
        ele.value="";
    }
}


function doStartup(){
    if (window.sw_startup_image) {
        document.getElementById("content").innerHTML="<img src='" + window.sw_startup_image + "'>";
    } else {
        document.getElementById("content").innerHTML="<img src='/dav/s/shoppingworld.info/cachedImages/2532.jpg'>";
    }


	entry_id=getParamFromLocation("entry_id");
	if (entry_id && entry_id>0){
		getEntryDataAndDisplay(entry_id);
	} else {
		getTopTenEntries();
	}
}

function getDateFormatted(){
    d=new Date();
    day=parseInt(d.getDate());
    month=parseInt(d.getMonth()+1);
    year=d.getYear();

    if (year<2000) {
        year+=1900;
    }

    if (day<10) {
        day="0"+day;
    }
    if (month<10) {
        month="0"+month;
    }
    return year + "" + month + "" + day;
}



function getTopTenEntries(){
    url=getCachePath()+"/shoppingWorldEntries/"+ getDateFormatted() +"/topten.json";

    if (window.geoip_country_code) {
        url+="."+window.geoip_country_code;
    }
    url+=".html";

	doAJAXGetCall(url, displayTopTenEntries);
}

function displayTopTenEntries(){
	if (xmlHttp.readyState == 4) {
		x=xmlHttp.responseText;
        var entriesData;
        if (x) {
            eval('entriesData='+x);


            for (i in entriesData) {
                doYahooTab(entriesData[i].entry_id, entriesData[i].hasAddress,entriesData[i].hasProfile);
            }
        }

        
	}
}

function getEntryDataAndDisplay(id){
	doAJAXGetCall(getCachePath()+'/shoppingWorldEntries/'+id+"/json.html", displaySelectedEntry);
}
function displaySelectedEntry(){
	if (xmlHttp.readyState == 4) {
		x=xmlHttp.responseText;
		if (x && x!="") {
			eval("var entryData="+x);
			doYahooTab(entryData.entry_id, entryData.hasAddress,entryData.hasProfile);
		} else {
			alert(xmlHttp.req.getAllResponseHeaders);
		}
	}
}

function doMap(){
	if (xmlHttp.readyState == 4) {
		x=Base64.decode(xmlHttp.responseText);
		//alert(x);
		eval("var mapData="+x);
		aMapData[mapData.entry_id]=mapData;

        longitude=mapData.longitude;
        latitude=mapData.latitude;
        aAddress=mapData;
        entry_id=mapData.entry_id;
        width=mapData.width;
        height=mapData.height;



        if (longitude && latitude) {
            setTimeout("showMap("+mapData.entry_id+")", 1000);
        }
	}
}


function showMap(entry_id){

    mapData=aMapData[entry_id];

    longitude=mapData.longitude;
    latitude=mapData.latitude;
    aAddress=mapData;
    entry_id=mapData.entry_id;
    width=mapData.width;
    height=mapData.height;
    if (longitude && latitude) {
        showMapWithLatLng(latitude,longitude, aAddress,entry_id, width,height);
    }
}

function showMapWithAddress(aAddress){

	address=aAddress.address;
	width=aAddress.width;
	height=aAddress.height;
	entry_id=aAddress.entry_id;

    

	geocoder = new GClientGeocoder();
	geocoder.getLatLng(
	address,
	function(point) {
		if (!point) {
			txt = "Could not find the Longitude and Latitude for your address\n"+address;
			//alert(txt);
		} else {

			if(!entry_id){
				entry_id=0;
			}
			//Display of the map
			showMapWithLatLng(point.y,point.x,aAddress,entry_id,width,height);
		}
	}
	);
}

function handleMap(id){
	// If there is mapData in the aMapData Array then call ShowMap with the data
	// else get the data and let the callback call the map
	if (!aMapData[id]) {
		doAJAXGetCall(getCachePath()+'/shoppingWorldEntries/'+id+"/map.html", doMap);
	} else {
        showMap(id);
		//showMapWithAddress(aMapData[id]);
	}
}

function getCachePath(){
    if (window.cachePath) {
        return window.cachePath;
    }
    hostname=self.location.hostname;
    hostname=hostname.replace(/^www\./, "");

    firstLetter=hostname.substring(0,1);
    basePath="/dav";
    cachePath=basePath+"/"+firstLetter+"/"+hostname;
    window.cachePath=cachePath;
    return cachePath;
}


function doEmbeddedYahooTab(entry_id,hasAddress,hasProfile){
    url="http://www.shoppingworld.info/modules/shoppingWorld/javascript/doEmbeddedYahooTab.js.php?entry_id="+entry_id+"&hasAddress="+hasAddress+"&hasProfile="+hasProfile;
    if (window.sw_tell_a_friend_button_src) {
        url+="&taf_but_src="+window.sw_tell_a_friend_button_src;
    }
    if (window.sw_view_coupon_button_src) {
        url+="&vc_but_src="+escape(window.sw_view_coupon_button_src);
    }
    loadScript(url, true);
    //alert(url);
}

function doYahooTab(entry_id,hasAddress,hasProfile){

	tabViews[entry_id]=new YAHOO.widget.TabView({id: 'yuitab_'+entry_id});



	tabViews[entry_id].addTab(new YAHOO.widget.Tab({
		label: window.XOOPS__MD_SW_ENTRY,
		dataSrc: getCachePath() +'/shoppingWorldEntries/'+entry_id+"/base.html",
		active: true
	}));


	if (hasAddress) {
		tabViews[entry_id].addTab(new YAHOO.widget.Tab({
			label: window.XOOPS__MD_SW_ADDRESS,
			dataSrc: getCachePath() + '/shoppingWorldEntries/'+entry_id+"/address.html",
			cacheData: true /* only load once */
		}));
	}
	if (hasProfile) {
		tabViews[entry_id].addTab(new YAHOO.widget.Tab({
			label: window.XOOPS__MD_SW_PROFILE,
			dataSrc: getCachePath() + '/shoppingWorldEntries/'+entry_id+"/profile.html",
			disabled: false,
			cacheData: true /* only load once */
		}));
	}

    /*tabViews[entry_id].addTab(new YAHOO.widget.Tab(
        {
            label: window.XOOPS__MD_SW_COUPON,
                disabled: true,
            dataSrc: '/dav/s/shoppingworld.info/shoppingWorldEntries/'+entry_id+"/coupon.html"
        }
    ));
    */


    /*tabViews[entry_id].addTab(new YAHOO.widget.Tab(
        {
            label: 'iFrametest',
            disabled: false,
            content: '<iframe marginwidth=0 marginheight=0 scrolling=no width=500 height=300 src="/googlemap.php"/>'
        }
    ));
    */



	tabViews[entry_id].appendTo('content');
    /*
    
    var test_function = new Function("handleMap("+entry_id+");");
	if (hasAddress) {
		tabViews[entry_id].getTab(1).addListener('click', test_function);
	}
	test_function = null;
    */




}

function handleGSAResponse() {
	if (xmlHttp.readyState == 4) {
		data=parse_and_replace_constants(xmlHttp.responseText);
        buildSearchResults(data);
	}
}


function buildSearchResults(text){
    data=text;

    if (sw_embedded){
        // For Rabattzo.de

        data=data.replace(/#E27E28/g, '#669900');
        data=data.replace(/#325771/g, '#000000');
        data=data.replace(/#F0F8FA/g, '#98CB00');
    }

    
    

    document.getElementById("content").innerHTML = data;



    var count=0;
    if (document.getElementById("sw_search_count")){
        count=document.getElementById("sw_search_count").value;
    }

    //alert(sw_search_ids.toString());

    if (count>0) {
        var entries_meta_data=document.getElementById("sw_entries_metadata").value.split(",");
        var search_results_bar=document.getElementById("search_results_bar");
        var search_results_bar2=search_results_bar.cloneNode(true);
        




        var search_results_bar_html=document.getElementById("search_results_bar").innerHTML;
        for (i in entries_meta_data){
            metaData=entries_meta_data[i].split("|");
            entry_id=metaData[0];
            hasAddress=(metaData[1]==1)?true:false;
            hasProfile=(metaData[2]==1)?true:false;
            //alert(metaData.toString());
            if (sw_embedded){
                doEmbeddedYahooTab(entry_id, hasAddress, hasProfile);
            } else {
                doYahooTab(entry_id, hasAddress, hasProfile);

            }
        }

        if (!sw_embedded){
            // Dont embed the second bar
            document.getElementById("content").appendChild(search_results_bar2);
        }

    }
}


function submitEmbeddedSearchForm(form) {
    sw_embedded=true;
    window.sw_embedded=true;
    var query = form.sw_search_query.value;
    var request_url = "http://www.shoppingworld.info/modules/shoppingWorld/search_gateway.js.php?q="+Base64.encode(query);

    loadScript(request_url, true);
    return false;
}


function submitSearchForm(form) {
    window.sw_embedded=false;
    var query = form.sw_search_query.value;
    var request_url = "/modules/shoppingWorld/search_gateway.php?q="+Base64.encode(query);
    if (window.sw_entries_per_page){
		request_url+="&entries_per_page="+window.sw_entries_per_page;
	}
    if (window.sw_pages_per_range){
		request_url+="&pages_per_range="+window.sw_pages_per_range;
	}


	if (document.getElementById("content")) {
		document.getElementById("content").innerHTML="<br><br><center><img src='/images/loading.gif'></center>";

		doAJAXGetCall(request_url, handleGSAResponse);
		//gsaRequestLoader = new sw.ContentLoader(request_url, handleGSAResponse);
	} else {
		alert("Problem.... Cannot find content layer");
		return false;
	}
	return false;
}



function onClickRange(range_first_element) {
	var query = document.getElementById("sw_search_query").value;
    start=(range_first_element-1)*7;

    var request_url = "/modules/shoppingWorld/search_gateway.php?q="+Base64.encode(query)+"&start="+start;
	if (window.sw_entries_per_page){
      request_url+="&entries_per_page="+window.sw_entries_per_page;
   }
    if (window.sw_pages_per_range){
      request_url+="&pages_per_range="+window.sw_pages_per_range;
   }

	doAJAXGetCall(request_url, handleGSAResponse);
}


function onClickSpelling(proposed_string) {
	var oInput = document.getElementById("sw_search_query");
	oInput.value = proposed_string;

	var query = proposed_string;
	var request_url = "/modules/shoppingWorld/search_gateway.php?q="+Base64.encode(query);
	doAJAXGetCall(request_url, handleGSAResponse);
}



var couponWin;
var current_entry_id;
var registration_form_text;

function onClickDisplayCoupon(entry_id){
    current_entry_id=entry_id;
    if (window.sw_embedded) {
        couponWinEmbedded = window.open ("","couponWinEmbedded", "height=700,width=600,menubar=no,scrollbars=no,resizable=no,,left=0,top=0");
        doEmbeddedDrawCouponWindow(entry_id);
        return;
    } else {
        couponWin = window.open ("","couponWin", "height=700,width=600,menubar=no,scrollbars=no,resizable=no,,left=0,top=0");
        url=getCachePath()+'/shoppingWorldEntries/'+entry_id+"/coupon.html";
        doAJAXGetCall(url, drawCouponWindow);

    }
    return;


    if (window.user_id) {
        couponWin = window.open ("","couponWin", "height=700,width=600,menubar=no,scrollbars=no,resizable=no,,left=0,top=0");
        url=getCachePath()+'/shoppingWorldEntries/'+entry_id+"/coupon.html";
        doAJAXGetCall(url, drawCouponWindow);
    } else {

        doLoginActionOnSucess=function(){
            loadScript("/include/user.js.php");
            //cClick();

            if (window.translations["XOOPS__MD_SW_LOGIN_OK"]) {
                showOverlib(window.translations["XOOPS__MD_SW_LOGIN_OK"],'');
            } else {
                cClick();
            }
            
            setTimeout("cClick()", 2000);


            //doAJAXGetCall(url, drawCouponWindow);
            //setTimeout("onClickDisplayCoupon("+entry_id+")", 1000);
        };
        //doLoginWindow(doLoginActionOnSucess);
        //doRegisterWindow();


        current_entry_id=entry_id;
        coupon_explaination_text=window.translations["XOOPS__MD_SW_COUPON_GENTEXT"];
        if (registration_form_text) {
            drawRegistrationArea(registration_form_text);
        } else {
        	loadScript("/include/validator.js");
            loadScript("/include/registerformValidation.js");
            doAJAXGetCall('/register.php?op=register_embedded&direct_login=1', getRegistrationForm);
        }
        


        //alert(tabViews[entry_id].toString());




    }
}

function getRegistrationForm(){
    if (xmlHttp.readyState == 4) {
        registration_form_text=xmlHttp.responseText;
        drawRegistrationArea(registration_form_text);
    }
}
function drawRegistrationArea(registration_form_text){
        window.overlibCaption=window.translations["XOOPS__US_USERREG"];
        window.overLibY=cursor.y;
        window.overLibX=cursor.x;
        showOverlib("<div style='width: 450px;'>"+coupon_explaination_text + "<br><br>"+ registration_form_text+"</div>");
    }

function drawRegistrationAreax(registration_form_text){
    tabViews[current_entry_id].addTab(new YAHOO.widget.Tab({
        label: window.translations["XOOPS__MD_SW_COUPON"],
        content: coupon_explaination_text + registration_form_text,
            active: true

    }),3);
}

function drawCouponWindow(){
    if (xmlHttp.readyState == 4) {
        coupon_content=xmlHttp.responseText;
        fillupCouponWindow(coupon_content, couponWin);
        return;
    }
}

function doEmbeddedDrawCouponWindow(entry_id){
    url="http://www.shoppingworld.info/modules/shoppingWorld/javascript/doEmbeddedDrawCouponWindow.js.php?entry_id="+entry_id;
    loadScript(url, true);
    //alert(url);
}





function fillupCouponWindow(coupon_content, cw){
    // cw is reference to the window object that was opened earlier
    // for the shoppingworld.info its couponWin
    // for the embedded versions its couponWinEmbedded

    coupon_content=coupon_content.replace(/%%YOUR_NAME%%/, '');
    cw.document.open();

    cw.document.write("<html><head><title></title>");
    cw.document.write('<link rel="stylesheet" type="text/css" media="all" href="/themes/shoppingworld/style.print.css" />');

    cw.document.write("</head><body bgcolor='#ffffff'><center>");
    cw.document.write(coupon_content);
    cw.document.write("<br><br><a href='javascript:window.print()'><img border=0 src=/modules/shoppingWorld/images/print_coupon.gif></a>");

    //
    cw.document.write('<img width=1 height=1 style="display: none" src="/modules/shoppingWorld/scripts/coupon_number.php?user_id='+window.user_id + '&entry_id=' + current_entry_id+'">');

    cw.document.write("</body></html>");
    cw.document.close();
    cw.focus();
}

function onClickPrintCoupon(coupon_title){
     var PSR_f1 = null;
     var coupon_content=document.getElementById('coupon_content').innerHTML;

     if (PSR_f1) {if(!PSR_f1.closed) PSR_f1.close();}
     PSR_f1 = window.open ('',"PSR_f1", "height=700,width=600,menubar=yes,scrollbars=yes,resizable=yes,,left=10,top=10"); ;
     PSR_f1.document.open();
     PSR_f1.document.write("<html><head><title>" + coupon_title + "</title>");
     PSR_f1.document.write('<link rel="stylesheet" type="text/css" media="all" href="/style.css.php?type=print&layout=print" />');
     PSR_f1.document.write("</head><body bgcolor='#ffffff'>"+coupon_content+"</body></html>");
     PSR_f1.document.close();
     PSR_f1.focus();
     PSR_f1.print();
     //PSR_f1.close();
}


function openSendLink(id){
    url="http://www.shoppingworld.info/modules/shoppingWorld/mail.php?op=form&entry_id="+id;
    if (window.my_affiliate_nr) {
        af_id=window.my_affiliate_nr;
        url=url+ '&' + 'af_id' + '=' + af_id;
    }

    sendLinkWindow=window.open(url, "sendEntryMail", "resizable=1,height=490,width=450");
    sendLinkWindow.focus();

}

function _openSendLink(id){
    url="http://www.shoppingworld.info/modules/shoppingWorld/mail.php?op=form&entry_id="+id;
    if (window.my_affiliate_nr) {
        af_id=window.my_affiliate_nr;
        url=url+ '&' + 'af_id' + '=' + af_id;
    }

    sendLinkWindow=window.open(url, "sendEntryMail", "height=450,width=450");
    sendLinkWindow.focus();


}


