// Clean --------------------------------------------- Start basic.js ---------------------------------------------

var MARGIN_WIDTH = 12;
var MARGIN_HEIGHT = 12;
var FOOTER_HEIGHT = 31;
var IS_BEST_FIT = false;


function fireConversionPixel(referral) {
   document.getElementById("conversionPixel").src = "/wixBeacon";
}

function handleUserServerResponse(action, success, errorCode, errorDescription, userJson, token) {
    var app = getFlashAppInstance();
    app.handleUserServerResponse(action, success, errorCode, errorDescription, userJson, token);
}

function addListener(win, eventName, handler) {
    if (win.addEventListener)
        win.addEventListener(eventName, handler, false);
    else if (win.attachEvent)
        win.attachEvent("on" + eventName, handler);
    else
        win["on" + eventName] = handler;
}

function openUrl(url) {
    try {
        var win = window.open(url, '_blank');
        win.focus();
        return true;
    } catch (e) {
        var img = new Image(0, 0);
        img.src = "http://flogger.wixpress.com/plebs?origin=Viewer&errType=openUrl&description=" + encodeURI(e.message) + "&apiCall=" + encodeURI(url) + "&appVersion=basic.js";
        return false;
    }
}

function openUrlNoMenu(url, vaildatePopup) {
	var errStr = "";
    try {
		errStr += "1";
        var popupBlocked = false;
        var screenSize = getPhysicalScreenDimensions();
		errStr += "2";
        var win = window.open(url, '_blank', "resizable=yes,menubar=no,status=no,titlebar=no,toolbar=no,channelmode=yes,width=" + screenSize.width + ",height=" + screenSize.height);
		errStr += "3";
        if (!win || win.closed || typeof win.closed == 'undefined') {
			errStr += "4";
            popupBlocked = true;
        } else {
			errStr += "5";
            win.focus();
        }
        if (vaildatePopup) {
			errStr += "6";
            var app = getFlashAppInstance();
			errStr += "7";
            app.popupFailure(popupBlocked);
			errStr += "8";
        }
        return true;
    } catch(e) {
        var img = new Image(0, 0);
        img.src = "http://flogger.wixpress.com/plebs?origin=Viewer&errType=openUrlNoMenu&description=er" + errStr + "_" + encodeURI(e.message) + "&apiCall=" + encodeURI(url) + "&appVersion=basic.js";
        return false;
    }
}

function isIE() {
    return (navigator.appName.indexOf("Microsoft") != -1);
}

function getPhysicalScreenDimensions() {
    var winW = 1024, winH = 768;
    if (isIE()) {
        winW = document.body.width;
        winH = document.body.height;
    } else {
        winW = screen.width;
        winH = screen.height;
    }
    return {width: (winW ), height: (winH )};
}

function getScreenDimensions() {
    var w = 0, h = 0;
    if (!window.innerWidth) {
        //strict mode
        if (!(document.documentElement.clientWidth == 0)) {
            w = document.documentElement.clientWidth;
            h = document.documentElement.clientHeight;
        } else { //quirks mode
            w = document.body.clientWidth;
            h = document.body.clientHeight;
        }
    } else { //w3c
        w = window.innerWidth;
        h = window.innerHeight;
    }
    return {width: (w - (2 * MARGIN_WIDTH)), height: (h - (2 * MARGIN_HEIGHT + (getFooter() ? FOOTER_HEIGHT : 0)))};
}

function getScrollOffset() {
    var x = 0,y = 0;
    if (self.pageYOffset) { // all except Explorer
        x = self.pageXOffset;
        y = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    } else if (document.body) {
        // all other Explorers
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    }
    return {x:x,y:y}
}

function getViewport() {
    var app = getFlashAppInstance();
    var dimensions = getScreenDimensions();
    var position = findFlashAppInstancePosition();
    var scroll = getScrollOffset();
    return {x:scroll.x, y:scroll.y, width:Math.min(dimensions.width - position.x, app.clientWidth), height:Math.min(dimensions.height - position.y, app.clientHeight)};
}

function findFlashAppInstancePosition() {
    return findElementPosition(getFlashAppInstance());
}

function findElementPosition(oElement) {
    if (typeof( oElement.offsetParent ) != 'undefined') {
        for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
        }
        return {x:posX, y:posY};
    } else {
        return {x:oElement.x, y:oElement.y};
    }
}

function getScreenSize() {
    var dimensions = getScreenDimensions();
    return dimensions.width + "," + dimensions.height;
}

function setTitle(title) {
    document.title = title;
}

function getFlashAppInstance() {
    return swfobject.getObjectById("app");
}

function getFooter() {
    var node = document.getElementById("wixfooter");
    if (node == null) {
        return document.getElementById("wixfooter1");
    }
    return node;
}

function setFooterWidth(width) {
    try {
        var footer = getFooter();
        if (footer) {
            if ((BrowserDetect.browser.indexOf("Firefox") >= 0) && (!useAppWidth) && (document.getElementById("wixfooter1") != null)) {
                footer.style.width = "100%";
            } else {
                footer.style.width = width + "px";
            }
        }
    } catch(e) {
    }
}


function setSize(width, height) {
    setFooterWidth(width);

    var app = getFlashAppInstance();
    app.width = width;
    app.height = height;

    var dimensions = getScreenDimensions();
    document.body.style.marginTop = height > dimensions.height ? "8px" : "0";
}

function createStyles(autoSize, width, height) {
    IS_BEST_FIT = (autoSize == "fitScreen");
    var cssText = new Array();
    cssText.push('<style type="text/css">');
    if (IS_BEST_FIT) {
        cssText.push('body {overflow:hidden !important}');
    } else {
        var dimensions = getScreenDimensions();
        if (height > dimensions.height) {
            cssText.push('body {margin-top:8px}');
        }
    }
    cssText.push('</style>');
    document.write(cssText.join(""));
}

//this function should call both the wix googlitics and the users (if the user have one)
function doGooglitics(fakeUrl) {
    pageTracker._trackPageview(fakeUrl);
    if (hasGoogleAnalytics) {
        pageTrackerUser._trackPageview(fakeUrl);
    }
}

//this function should call only the wix googlitics
function doGoogliticsWix(fakeUrl) {
    pageTracker._trackPageview(fakeUrl);
}

//this function should call only the user googlitics (if the user doesnt have one the function should be empty
function doGoogliticsUser(fakeUrl) {
    if (null != userGoogleAnalytics && "" != userGoogleAnalytics) {
        if (hasGoogleAnalytics) {
            pageTrackerUser._trackPageview(fakeUrl);
        }
    }
}

function gaSSDSLoad(acct) {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
            pageTracker,
            s;
    s = document.createElement('script');
    s.src = gaJsHost + 'google-analytics.com/ga.js';
    s.type = 'text/javascript';
    s.onloadDone = false;
    function initPageTrackers() {
        pageTracker = _gat._getTracker(acct);
        pageTracker._trackPageview();

        if (hasGoogleAnalytics) {
            pageTrackerUser = _gat._getTracker(userGoogleAnalytics);
            pageTrackerUser._initData();
            pageTrackerUser._trackPageview();
        }
    }

    s.onload = function () {
        s.onloadDone = true;
        initPageTrackers();
    };
    s.onreadystatechange = function() {
        if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
            s.onloadDone = true;
            initPageTrackers();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}

function pageOnLoad() {
    gaSSDSLoad(wixGoogleAnalytics);
}

function pageOnResize() {
    var dimensions = getScreenDimensions();
    var app = getFlashAppInstance();
    if (app != null) {
        try {
            app.onScreenResize(dimensions.width, dimensions.height);
        } catch(e) {
        }
    }
    adjustFooterWidth();
    return false;
}

function setHistoryFrame(adress, additionalInfo) {
    try {
        var page_name = adress.substr(8, adress.indexOf(',') - 8);
        if (additionalInfo != null && additionalInfo.length > 0) {
            page_name = page_name + '_' + additionalInfo;
        }
        page_name = page_name + '.html';
        var ifrm = document.getElementById("historyframe");
        if (ifrm != null) {
            ifrm.src = "/siteBackHtml?adress=" + adress + '&additionalInfo=' + additionalInfo;
        }
    } catch(ex) {
        var ifrm = document.getElementById("historyframe");
        if (ifrm != null) {
            ifrm.src = "/siteBackFiles/siteBack.html?adress=" + adress + '&additionalInfo=' + additionalInfo;
        }
    }
}

function onHistoryFrameLoaded(adress, additionalInfo) {
    var app = getFlashAppInstance();
    if (app != null) {
        try {
            app.onHistoryFrameLoaded(adress, additionalInfo);
        } catch(e) {
        }
    }
}

addListener(window, "load", function() {
    pageOnLoad();
});
addListener(window, "resize", function() {
    pageOnResize();
});

// ----------------------------------------------------------------------------------------------------------------------

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.userAgent,
            subString: "iPhone",
            identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();


// =============================================== settings (vars) ======================================================
var desing_wix = "http://www.wix.com/create/website";
var free_web = "Make a free website";
var campaign_id = "sf_footer";
//var experiment_id =  <social network>_<site_id>
var twitter_txt = "Check out this @Wix site ";
var addrWithParamsNotEnc = "" + window.location + "?client_bi=true&utm_campaign=" + campaign_id + "&experiment_id=";
var addrWithParams = "" + window.location + encodeURIComponent("?client_bi=true&utm_campaign=" + campaign_id + "&experiment_id=");
var iconImageAddr = "";
//var floggerAddr = "http://frog2.wix.com";
var floggerAddr = "http://frog.wix.com";  //  for nine.wixpress
var domain = "";

function buildFootbar() {
    var oldDomain = "" + usersDomain;
    domain = oldDomain.replace("users.", "static.");

    iconImageAddr = "http://" + domain + "/media/" + siteIconName;

    var suf = document.getElementById("wfa1");
    if (suf.href) {
        //	suf_href = suf.href;
        desing_wix = suf.href;
    }
    if (suf.innerHTML) {
        suf_txt = suf.innerHTML;
        free_web = suf.innerHTML;
    }

    if (BrowserDetect.browser.indexOf("Firefox") >= 0) {
        buildFootbarFF();
        setTimeout("adjustFooterWidth();", 500);
    } else {
        setTimeout("buildFootbarAll();", 500);
    }

    // call inform
    inform(floggerAddr + "/footer_bi?event_id=1&site_id=" + biSequence + "&target_sn=0");
}

var useAppWidth = false;
function adjustFooterWidth() {
    var wf = document.getElementById("wixfooter1");
    if (wf == null) {
        return;
    }

    if (BrowserDetect.browser.indexOf("Firefox") >= 0) {
        if (useAppWidth) {
            var position = findFlashAppInstancePosition();
            wf.style.left = position.x + "px";
        } else {
            wf.style.left = "0px";
            wf.style.width = "100%";
        }
    } else {
        var position = findFlashAppInstancePosition();
        var app = getFlashAppInstance();
        var h = app.clientHeight;
        wf.style.left = position.x + "px";
        wf.style.top = (app.clientHeight + position.y) + "px";
    }
}

function buildFootbarFF() {
    var bdy = document.body;
    var elem0 = document.getElementById("wixfooter1");
    if (elem0) {
        var parent = elem0.parentNode;
        parent.removeChild(elem0);
    }

    var footerElem = document.createElement("div");  //
    footerElem.id = "wixfooter1";  //
    footerElem.style.backgroundColor = "#F0F0F0";
    footerElem.style.top = "auto";
    footerElem.style.bottom = "0px";
    footerElem.style.position = "fixed";
    footerElem.style.margin = "0 auto";

    bdy.appendChild(footerElem);

    buildPrefix(footerElem);
    buildFacebook(footerElem);
    buildTwitter(footerElem);
    buildBuzz(footerElem);
    buildDigg(footerElem);
    buildStumble(footerElem);
    buildSuffix(footerElem);
}

function buildFootbarAll() {
    var bdy = document.body;
    var elem0 = document.getElementById("wixfooter1");
    if (elem0) {
        var parent = elem0.parentNode;
        parent.removeChild(elem0);
    }

    var footerElem = document.createElement("div");
    footerElem.id = "wixfooter1";
    footerElem.align = "left";
    var position = findFlashAppInstancePosition();
    footerElem.style.position = "absolute";
    footerElem.style.left = position.x + "px";
    var app = getFlashAppInstance();
    var h = app.clientHeight;
    footerElem.style.top = (app.clientHeight + position.y) + "px";

    bdy.appendChild(footerElem);
    buildPrefix(footerElem);
    buildFacebook(footerElem);
    buildTwitter(footerElem);
    buildBuzz(footerElem);
    buildDigg(footerElem);
    buildStumble(footerElem);
    buildSuffix(footerElem);
}

function buildPrefix(footerElem) {
    var tagA = document.createElement("a");
    tagA.href = desing_wix;
    tagA.title = "website builder";
    tagA.id = "a0id";
    var L1 = document.createElement("span");
    L1.className = "logo";
    tagA.appendChild(L1);
    footerElem.appendChild(tagA);

    var imLine = document.createElement("img");
    imLine.src = "http://" + domain + "/client/images/Line.png";
    imLine.align = "left";
    imLine.style.height = "21px";
    footerElem.appendChild(imLine);

    var tagA1 = document.createElement("a");
    tagA1.title = "Website builder";
    tagA1.className = "link1";
    tagA1.align = "left";
    tagA1.innerHTML = "&nbsp;&nbsp;Share this site: ";
    footerElem.appendChild(tagA1);
}

function buildTwitter(footerElem) {
    var tagA = document.createElement("a");
    tagA.title = "Share site on Twitter";
    tagA.target = "_blank";
    tagA.id = "a2id";
    var experiment_id = getSocialCode("Twitter") + "_" + biSequence;
    tagA.href = "http://twitter.com/home?status=" + twitter_txt + addrWithParams + experiment_id;
    tagA.onclick = new Function('inform("' + floggerAddr + '/footer_bi?event_id=2&site_id=' + biSequence + '&target_sn=2")');
    footerElem.appendChild(tagA);

    shorten_func(addrWithParamsNotEnc + experiment_id, "twitter");

    var im = document.createElement("img");
    im.alt = "Share site on Twitter";
    im.border = "0";
    im.hspace = "6";
    im.align = "left";
    im.src = "http://" + domain + "/client/images/twitter.png";
    im.style.marginLeft = '7px';
    im.style.width = "17px";
    im.style.height = "17px";
    im.style.marginTop = '3px';
    im.id = "twitterId";
    tagA.appendChild(im);
}


function buildStumble(footerElem) {
    var tagA = document.createElement("a");
    var experiment_id = getSocialCode("StumbleUpon") + "_" + biSequence;
    tagA.href = "http://www.stumbleupon.com/submit?url=" + addrWithParams + experiment_id + "&title=WIX, WIX, WIX";
    ;
    tagA.onclick = new Function('inform("' + floggerAddr + '/footer_bi?event_id=2&site_id=' + biSequence + '&target_sn=5")');
    tagA.title = "Share site on StumbleUpon";
    tagA.id = "a4id";
    tagA.target = "_blank";
    tagA.rel = "external";
    footerElem.appendChild(tagA);

    var im = document.createElement("img");
    im.alt = "Share site on StumbleUpon";
    im.border = "0";
    im.hspace = "6";
    im.align = "left";
    im.src = "http://" + domain + "/client/images/stumbleupon.png";
    im.style.width = "17px";
    im.style.height = "17px";
    im.style.marginTop = '3px';
    tagA.appendChild(im);
}

function buildDigg(footerElem) {
    var tagA = document.createElement("a");
    var experiment_id = getSocialCode("Digg") + "_" + biSequence;
    tagA.href = "http://digg.com/submit?phase=2&url=" + addrWithParams + experiment_id + "&title=WIX, WIX, WIX";
    tagA.title = "Share site on Digg";
    tagA.id = "a5id";
    tagA.onclick = new Function('inform("' + floggerAddr + '/footer_bi?event_id=2&site_id=' + biSequence + '&target_sn=4")');
    tagA.rel = "external";
    tagA.target = "_blank";
    footerElem.appendChild(tagA);

    //  shorten_func(addrWithParamsNotEnc + experiment_id, "digg");

    var im = document.createElement("img");
    im.alt = "Share site on Digg";
    im.border = "0";
    im.hspace = "6";
    im.align = "left";
    im.src = "http://" + domain + "/client/images/digg.png";
    im.style.width = "17px";
    im.style.height = "17px";
    im.style.marginTop = '3px';
    tagA.appendChild(im);
}


function buildFacebook(footerElem) {
    var tagA = document.createElement("a");
    tagA.title = "Share site on Facebook";
    tagA.id = "a6id";
    var experiment_id = getSocialCode("Facebook") + "_" + biSequence;
    tagA.href = "http://www.facebook.com/share.php?u=" + addrWithParams + experiment_id;

    tagA.onclick = new Function('return start_publish()');
    tagA.target = "_blank";

    footerElem.appendChild(tagA);

    var im = document.createElement("img");
    im.alt = "Share site on Facebook";
    im.border = "0";
    im.hspace = "6";
    im.align = "left";
    im.src = "http://" + domain + "/client/images/facebook.png";
    im.style.width = "17px";
    im.style.height = "17px";
    im.style.marginTop = '3px';
    tagA.appendChild(im);
}

function buildBuzz(footerElem) {
    var tagA = document.createElement("a");
    tagA.title = "Share site on Google Buzz";
    var experiment_id = getSocialCode("Buzz") + "_" + biSequence;
    tagA.href = "http://www.google.com/buzz/post?url=" + addrWithParams + experiment_id + "&imageurl=" + iconImageAddr;

    tagA.onclick = new Function('inform("' + floggerAddr + '/footer_bi?event_id=2&site_id=' + biSequence + '&target_sn=3")');
    tagA.id = "a3id";
    tagA.target = "_blank";
    footerElem.appendChild(tagA);

    var im = document.createElement("img");
    im.alt = "Share site on Google Buzz";
    im.border = "0";
    im.hspace = "6";
    im.align = "left";
    im.src = "http://" + domain + "/client/images/buzz.png";
    im.style.width = "17px";
    im.style.height = "17px";
    im.style.marginTop = '3px';
    tagA.appendChild(im);
}

function buildSuffix(footerElem) {
    var tagA = document.createElement("a");
    tagA.id = "wfa1";
    tagA.href = desing_wix;
    tagA.className = "link2";
    tagA.title = "Free website";
    tagA.innerHTML = free_web;
    footerElem.appendChild(tagA);
    var node = document.getElementById("wfa1");
    node.onmouseover = closeStatus;
    node.onmouseout = closeStatus;
}

function inform(name) {
    new Image(0, 0).src = name;
}

function start_publish() {
    var username = "";
    var docname = "";
    var url = addrWithParams + "1_" + biSequence;

    var thumbnail = iconImageAddr;
    var description = "";
    var flashvars = "";
    var message = "";
    publishToFacebook(username, docname, url, thumbnail, description, flashvars, message);
    inform(floggerAddr + "/footer_bi?event_id=2&site_id=" + biSequence + "&target_sn=1");
    return false;
}

function publishToFacebook(username, docname, url, thumbnail, description, flashvars, msg) {
    var share = {
        method: 'stream.share',
        u: url,
        t: docname
    };

    FB.ui(share, function(response) {
    });
}

function getSocialCode(name) {
    var codes = {
        "Facebook":"1",
        "Twitter":"2",
        "Buzz":"3",
        "Digg":"4",
        "StumbleUpon":"5"
    }
    for (x in codes) {
        if (x.toUpperCase() == name.toUpperCase()) {
            return codes[x];
        }
    }
    return null;
}

function closeStatus() {
    var setStatus = " ";
    window.status = setStatus;
    return true;
}


var waitTime = 100;
var sss = '';
// Bit.ly API  
function shorten_func(data, targ) {
    data = data + "&tt=" + Math.random();
    BitlyCB.shortenResponse = function(data) {
        sss = '';
        var first_result;
        // Results are keyed by longUrl, so we need to grab the first one.
        for (var r in data.results) {
            first_result = data.results[r];
            break;
        }
        sss = first_result["shortUrl"].toString();
    }
    BitlyClient.shorten(data, 'BitlyCB.shortenResponse');

    if (targ.indexOf("twitter") >= 0) {
        callTwitterValue();
    } else if (targ.indexOf("digg") >= 0) {
        callDiggValue();
    }
}

function callTwitterValue() {
    if ((sss.indexOf("http") >= 0) && (document.getElementById("a2id"))) {
        getTwitterShort();
    } else {
        window.setTimeout("callTwitterValue();", 100);
    }
}

function getTwitterShort() {
    var node = document.getElementById("a2id");
    node.href = "http://twitter.com/home?status=" + twitter_txt + sss;
}

function callDiggValue() {
    if ((sss.indexOf("http") >= 0) && (document.getElementById("a5id"))) {
        getDiggShort();
    } else {
        window.setTimeout("callDiggValue();", 100);
    }
}

function getDiggShort() {
    var node = document.getElementById("a5id");
    node.href = "http://digg.com/submit?phase=2&url=" + sss;
}

